html/js/javascript自动触发select-options下拉框实现方案
支持自动选中某项,同时触发变化事件。
例子代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<select id="pid" onchange="gradeChange()">
<option id='opt1' value="1">选项一</option>
<option id='opt2' value="2">选项二</option>
</select>
<button id='testBtn' onclick="test()">测试</button>
<script type="text/JavaScript">
function gradeChange() {
let objS = document.getElementById("pid");
let grade = objS.options[objS.selectedIndex].value;
alert(grade);
}
function test() {
let testBtn = document.getElementById('testBtn');
let objS = document.getElementById("pid");
let opt2 = document.getElementById("opt2");
//objS.setAttribute("size",objS.options.length);
objS.selectedIndex = 1;
let evt_change = document.createEvent('HTMLEvents');
evt_change.initEvent('change', true, true);
objS.dispatchEvent(evt_change);
}
</script>
</body>
</html>