首頁 >web前端 >js教程 >js觸發select onchange事件的小技巧_javascript技巧

js觸發select onchange事件的小技巧_javascript技巧

WBOY
WBOY原創
2016-05-16 16:40:201765瀏覽

select 或text的onchange事件需要手動(透過鍵盤輸入)改變select或text的值才能觸發,如果在js中給select或text賦值,則無法觸發onchang事件,
例如,在頁面載入完成以後,需要觸發一個onChange事件,在js中用document.getElementById("province").value="湖北";直接給select或text賦值是不行的,要實現手動觸發onchange事件,需要在js將select賦值後,加入下面的語句

document.getElementById("province").fireEvent('onchange') 來實作,

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">

var provinces = new Array();
provinces["湖北"] = ["武汉","襄阳","随州","宜昌","十堰"];
provinces["四川"] = ["成都","内江","达州"];
provinces["河南"] =["郑州","南阳","信阳","漯河"];
function changeProvince()
{
var prov = document.getElementById("province").value;
var city =document.getElementById("city");
city.options.length =0;
for(var i in provinces[prov])
{
city.options.add(new Option(provinces[prov][i],provinces[prov][i]));
}
}
window.onload = function(){
var province = document.getElementById("province");

for(var index in provinces)
{
//alert(index);
province.options.add(new Option(index,index));
}
province.fireEvent("onchange");
};
</script>
</head>
<body>
省份:<select id="province" onchange= "changeProvince()"></select>
城市:<select id="city"></select>

</body>
</html>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn