HTML:js应用---下拉框联动(省市二级下拉框联动,含代码)
以下是一个简单的HTML和JavaScript代码示例,实现了省市二级下拉框联动的功能。
<!DOCTYPE html>
<html>
<head>
<title>下拉框联动示例</title>
<script>
window.onload = function() {
var provinces = ["省份A", "省份B", "省份C"];
var cities = {
"省份A": ["城市A1", "城市A2", "城市A3"],
"省份B": ["城市B1", "城市B2", "城市B3"],
"省份C": ["城市C1", "城市C2", "城市C3"]
};
var provinceSelect = document.getElementById("province");
var citySelect = document.getElementById("city");
// 填充省份下拉框
for (var i = 0; i < provinces.length; i++) {
var option = document.createElement("option");
option.value = provinces[i];
option.text = provinces[i];
provinceSelect.appendChild(option);
}
// 省份下拉框变化事件
provinceSelect.onchange = function() {
citySelect.options.length = 0; // 清空城市下拉框
var province = provinceSelect.value;
var cityOptions = cities[province];
if (cityOptions) {
for (var i = 0; i < cityOptions.length; i++) {
var option = document.createElement("option");
option.value = cityOptions[i];
option.text = cityOptions[i];
citySelect.appendChild(option);
}
}
};
};
</script>
</head>
<body>
<select id="province">
<option value="">选择省份</option>
</select>
<select id="city">
<option value="">选择城市</option>
</select>
</body>
</html>
这段代码在页面加载完成后,会自动填充省份下拉框,并为省份下拉框添加onchange
事件监听器,当省份发生变化时,会更新城市下拉框的内容。这个例子使用了JavaScript创建了<option>
元素,并动态地将它们添加到相应的<select>
元素中。
评论已关闭