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>