我正在尝试更改选择标签的选定索引。但是通过 jquery 更改索引时不会触发 onchange 事件。
我正在动态地为选择标签创建选项。我不会知道选项标签的值。
还有其他方法可以实现吗?
这是我的代码片段。请随意提供意见。
function callFunc(obj) {
console.log(obj.value);
}
setTimeout(() => {
$("#select1")[0].selectedIndex = 2;
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1" onchange="callFunc(this);">
<option value='0'>select ....</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
..或使用VanillaJS(喜欢event constructors
over createEvent
):
function setSelectedIndex(el, index){
el.selectedIndex = index;
el.dispatchEvent(new Event('change', { bubbles: true }));
}
setSelectedIndex(select1, 2);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)