JS实现多选select下拉框选中项列表展示及代码问题修复
多选下拉选中项列表渲染实现
原有代码问题
- 脚本仅在页面初始加载时执行,未绑定下拉框的选择变化事件,用户操作选项后页面不会同步更新
- 遍历逻辑未判断选项的
selected选中状态,无法识别用户选中的项 - 存在语法错误:字符串拼接时引号不闭合,混用
document.write和innerHTML赋值,逻辑混乱 - 虽给
<select>标签添加了multiple属性,但未编写对应多选场景的处理逻辑
实现逻辑
- 给多选下拉框绑定
change事件,每次用户勾选/取消勾选选项时触发更新 - 事件触发后遍历所有选项,筛选出
selected属性为true的已选中项 - 清空列表容器原有内容,将所有选中项拼接为列表项插入容器
- 页面初始化时执行一次更新逻辑,兼容默认选中项的场景
完整可运行代码
<body> <label for="issue">Issue Type:</label> <!-- 操作提示:Windows按住Ctrl、Mac按住Command点击选项即可多选 --> <select multiple name="issue" id="issue"> <option value="passport">passport</option> <option value="selfie">selfie</option> <option value="nationalId">nationalId</option> </select> <p> you are missing the following information:</p> <ul id="issue-type"></ul> <script> const issueSelect = document.getElementById('issue'); const issueList = document.getElementById('issue-type'); function updateSelectedList() { // 清空旧的列表内容 issueList.innerHTML = ''; // 遍历所有选项,筛选已选中项渲染 for (const option of issueSelect.options) { if (option.selected) { const listItem = document.createElement('li'); listItem.textContent = option.textContent; issueList.appendChild(listItem); } } } // 初始化渲染 updateSelectedList(); // 绑定选择变化事件,实时更新 issueSelect.addEventListener('change', updateSelectedList); </script> </body>
使用说明
- 多选操作方式:Windows系统按住
Ctrl键点击选项,Mac系统按住Command键点击选项,即可选中多个项/取消单个项的选中状态 - 选中项变化时,下方无序列表会自动同步展示所有当前选中的选项
内容的提问来源于stack exchange,提问作者mbt
相关产品推荐
相关产品推荐

