onchange 事件
<body>
<select id="province" onchange="func1()">
<option value="shandong">山东</option>
<option value="hebei">河北</option>
<option value="beijing">北京</option>
</select>
</body>
<script>
function func1(){
var pro = document.getElementById("province");
console.log(pro.value)
}
</script>
使用字典方式添加数据
一级数据显示
<body>
<select id="province" >
</select>
</body>
<script>
data = {"广东省":["广州","佛山"],"北京":["海淀","廊坊"], "海南省":["三亚","海口"]};
var pro = document.getElementById("province");
for (var i in data){
var option_pro = document.createElement("option");
option_pro.innerHTML=i;
pro.appendChild(option_pro);
}
</script>
二级数据联动 方式一
<body>
<select id="province" onchange="func1(this)" >
</select>
<select id="city"></select>
</body>
<script>
data = {"广东省":["广州","佛山"],"北京":["海淀","廊坊"], "海南省":["三亚","海口"]};
var pro = document.getElementById("province");
var city = document.getElementById("city");
for (var i in data){
var option_pro = document.createElement("option");
option_pro.innerHTML=i;
pro.appendChild(option_pro);
}
function func1(self){
//console.log((self.options[self.selectedIndex]).innerHTML);
var choice = (self.options[self.selectedIndex]).innerHTML;
var options = city.children;
for (var k=0; k<options.length; k++){
city.removeChild(options[k--]);
}
for (var i in data[choice]){
var option_city = document.createElement("option");
option_city.innerHTML = data[choice][i];
city.appendChild(option_city);
}
}
</script>
二级数据联动 方式二
<body>
<select id="province" onchange="func1(this)" >
</select>
<select id="city"></select>
</body>
<script>
data = {"广东省":["广州","佛山"],"北京":["海淀","廊坊"], "海南省":["三亚","海口"]};
var pro = document.getElementById("province");
var city = document.getElementById("city");
for (var i in data){
var option_pro = document.createElement("option");
option_pro.innerHTML=i;
pro.appendChild(option_pro);
}
function func1(self){
//console.log((self.options[self.selectedIndex]).innerHTML);
var choice = (self.options[self.selectedIndex]).innerHTML;
city.options.length=0;
for (var i in data[choice]){
var option_city = document.createElement("option");
option_city.innerHTML = data[choice][i];
city.appendChild(option_city);
}
}
</script>
原文地址:https://www.cnblogs.com/klvchen/p/10364333.html
时间: 2024-10-22 10:15:29