使用 JavaScript 更改 <select> 的选项和触发事件 [英] Change <select>'s option and trigger events with JavaScript
问题描述
如何使用 JavaScript 更改 HTML 的选项(没有任何库,如 jQuery),同时触发与用户进行更改相同的事件?
How can I change an HTML <select>
's option with JavaScript (without any libraries like jQuery), while triggering the same events as if a user had made the change?
例如使用以下代码,如果我用鼠标更改选项,则会触发一个事件(即运行 onchange
).但是,当我使用 JavaScript 更改选项时,它不会触发任何事件.当使用 JavaScript 选择一个选项时,是否可以触发与 onclick
、onchange
等相关的事件处理程序?
For example using following code, if I change the option with my mouse then an event triggers (i.e. onchange
is run). However, when I change the option using JavaScript then it doesn't fire any event. Is it possible to fire trigger associated event handlers like onclick
, onchange
, etc., when an option is selected with JavaScript?
<select id="sel" onchange='alert("changed")'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" onclick='document.getElementById("sel").options[1].selected = true;' value="Change option to 2" />
推荐答案
很遗憾,您需要手动触发 change
事件.使用事件构造器将是最好的解决方案.
Unfortunately, you need to manually fire the change
event. And using the Event Constructor will be the best solution.
var select = document.querySelector('#sel'),
input = document.querySelector('input[type="button"]');
select.addEventListener('change',function(){
alert('changed');
});
input.addEventListener('click',function(){
select.value = 2;
select.dispatchEvent(new Event('change'));
});
<select id="sel" onchange='alert("changed")'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3' selected>Three</option>
</select>
<input type="button" value="Change option to 2" />
当然,IE 不支持 Event
构造函数.所以你可能需要用这个 polyfill:
And, of course, the Event
constructor is not supported in IE. So you may need to polyfill with this:
function Event( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
这篇关于使用 JavaScript 更改 <select> 的选项和触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!