You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用原生JavaScript实现在当前页显示选中项及跨页传参展示

原生JavaScript复选框选中值展示与URL传参解决方案

一、在表单上方展示选中的复选框值

首先添加用于展示的容器,同时修正获取选中项的逻辑:

修正后的HTML结构

<div id="show">You selected: </div>
<form onsubmit="handleSubmit(event)">
  <div id="myToys" >
    <input type="checkbox" id="v1" name="toy[]" value="Car">
    <label for="v1"> Car</label><br>

    <input type="checkbox" id="v2" name="toy[]" value="Boat">
    <label for="v2"> Boat</label><br>

    <input type="checkbox" id="v3" name="toy[]" value="Airplane">
    <label for="v3"> Airplane</label><br><br>
  </div>
  <input type="submit" value="Submit">
</form>

对应的JavaScript代码

function handleSubmit(e) {
  // 阻止表单默认提交行为,避免页面刷新
  e.preventDefault();
  
  // 获取所有选中的复选框
  const checkedToys = document.querySelectorAll('input[name="toy[]"]:checked');
  // 收集选中项的值,转为数组后拼接成字符串
  const selectedValues = Array.from(checkedToys).map(item => item.value);
  // 更新展示容器内容
  document.getElementById('show').textContent = `You selected: ${selectedValues.join(', ')}`;
  
  // 调用传参函数跳转到目标页面
  sendToPage2(selectedValues);
}

关键修正点

  • 将onsubmit事件绑定在<form>标签上,通过event.preventDefault()阻止默认提交行为
  • 使用document.querySelectorAll('input[name="toy[]"]:checked')精准获取选中的复选框
  • 修正原代码中label的for属性与复选框id不匹配的问题

二、通过URLSearchParams传递选中项到另一页面

在上述代码基础上添加传参函数,并创建目标页面读取参数:

1. 页面1的传参函数

在之前的<script>中添加以下函数:

function sendToPage2(selectedToys) {
  const params = new URLSearchParams();
  // 逐个添加选中项,生成多个`toy[]=xxx`格式的参数
  selectedToys.forEach(toy => {
    params.append('toy[]', toy);
  });
  
  // 拼接URL并跳转
  const url = `page2.html?${params.toString()}`;
  window.location.href = url;
}

2. 页面2(page2.html)的展示代码

创建page2.html,添加以下代码读取并展示URL参数:

<div id="result"></div>
<script>
  // 解析当前页面的URL查询参数
  const params = new URLSearchParams(window.location.search);
  // 获取所有`toy[]`参数的值
  const selectedToys = params.getAll('toy[]');
  
  // 渲染展示结果
  const resultDiv = document.getElementById('result');
  if (selectedToys.length > 0) {
    resultDiv.textContent = `Selected toys: ${selectedToys.join(', ')}`;
  } else {
    resultDiv.textContent = 'No toys selected';
  }
</script>

关键说明

  • 使用URLSearchParams的append方法添加多个同名参数,符合HTTP表单提交的规范
  • 页面2通过getAll('toy[]')获取所有选中项的值,支持多选场景

内容的提问来源于stack exchange,提问作者JappperCat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 19:25:27