使用html和js写出有多级联动的下拉框,需要根据后端传入的数据动态更新的下拉框。
1条回答 默认 最新
ಥ_ಥʕᵔᴥᵔʔ 2024-01-11 18:49关注HTML部分:
<form> <label for="parent">选择父级选项:</label> <select id="parent" name="parent"> <option value="1">选项1</option> <option value="2">选项2</option> <option value="3">选项3</option> </select> <label for="child">选择子级选项(基于父级):</label> <select id="child" name="child"> <option value="1">选项1</option> <option value="2">选项2</option> <option value="3">选项3</option> </select><br> <label id="grandchild" for="grandchild">选择孙子级选项(基于子级):</label><br> <input type="checkbox" id="grandchild1"> 选项1 <input type="checkbox" id="grandchild2"> 选项2 <input type="checkbox" id="grandchild3"> 选项3 </form>JavaScript部分:
// 获取父级和子级下拉框的值 var parent = document.getElementById("parent"); var child = document.getElementById('child'); var grandchild = document.getElementById("#grandchild"); // 监听父级下拉框的变化 parent.addEventListener('change', function () { // 获取当前选中的值 var selectedParent = parent.value; // 清除子级下拉框 while (child.firstChild) { child.removeChild(child.firstChild); } //根据父级的值获取子级选项 switch (selectedParent) { case '1': child.options[0] = new Option('选项1a', '1a'); child.appendChild(new Option('选项1b', '1b')); break; case '2': child[0].disabled = true; child[1].disabled = true child.insertBefore(new Option('子选项2a', '2a'), child[1]); break; case "3": child.removeAll(); break; } // 监听子级下拉框变化 child.addEventListener('change' , function() { var selectedChild = child.value; // 根据子级的值获取孙子级选项 switch (selectedChild) { case '1a': grandchild.append('<input type="checkbox"/>'); break; case '2a': var input = document.createElement('input'); input.type = 'checkbox'; input.id = 'grandchild2a'; input[0].name = 'grandchild[]'; grandchild[0].appendChild(input); break; } }); } );本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报