使用Html5的数据属性(data-*)Map级联关系,代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Select级联</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type=text/javascript>
$(document).ready(function () {
//获取子select的option
let childOptions = $("select[name='children']").find("option");
$("select[name='parent']").change(cascadeSelect);
//级联过滤方法
function cascadeSelect(event) {
//获取选中index及value
let index = event.target["selectedIndex"];
let item = event.target[index].value;
//过滤方法1
let options = childOptions.filter(function () {
return (this.value == "" || this.dataset.parent == item);
});
//过滤方法2
// let options = Array.from(childOptions).filter(function (option) {
// return option.value == "" || option.dataset.parent == item
// });
//清空子select,重新绑定,并设定默认选中项
$("select[name='children']").empty().append(options);
$("select[name='children']").find("option[value='']").prop("selected", true);
}
});
</script>
</head>
<body>
<select name="parent">
<option value="" selected>请选择</option>
<option value="1">选项1</option>
<option value="2">选项2</option>
<option value="3">选项3</option>
<option value="4">选项4</option>
<option value="5">选项5</option>
</select>
<select name="children">
<!-- 使用data-*属性Map级联关系 -->
<option data-parent="" value="" selected>请选择</option>
<option data-parent="1" value="1">子选项1-1</option>
<option data-parent="1" value="2">子选项1-2</option>
<option data-parent="1" value="3">子选项1-3</option>
<option data-parent="1" value="4">子选项1-4</option>
<option data-parent="1" value="5">子选项1-5</option>
<option data-parent="2" value="6">子选项2-1</option>
<option data-parent="2" value="7">子选项2-2</option>
<option data-parent="2" value="8">子选项2-3</option>
<option data-parent="2" value="9">子选项2-4</option>
<option data-parent="3" value="10">子选项3-1</option>
<option data-parent="3" value="11">子选项3-2</option>
<option data-parent="3" value="12">子选项3-3</option>
<option data-parent="4" value="13">子选项4-1</option>
<option data-parent="4" value="14">子选项4-2</option>
<option data-parent="4" value="15">子选项4-3</option>
<option data-parent="4" value="16">子选项4-4</option>
<option data-parent="4" value="17">子选项4-5</option>
<option data-parent="5" value="18">子选项5-1</option>
<option data-parent="5" value="19">子选项5-2</option>
<option data-parent="5" value="20">子选项5-3</option>
</select>
</body>
</html>