更改< select>的选项并使用JavaScript触发事件 [英] Change <select>'s option and trigger events with JavaScript
问题描述
如何用JavaScript(没有像jQuery之类的库)更改HTML < select>
的选项,同时触发相同的事件,就像用户创建例如使用下面的代码,如果我用鼠标更改选项,则会触发一个事件(即 onchange
正在运行)。但是,当我使用JavaScript更改选项时,它不会触发任何事件。当使用JavaScript选择一个选项时,是否可以触发与触发相关的事件处理程序,如 onclick
, onchange
等。 ?
< select id =selonchange ='alert(changed)'>
< option value ='1'>一个< / option>
< option value ='2'>两个< / option>
< option value ='3'>三< / option>
< / select>
< input type =buttononclick ='document.getElementById(sel)。options [1] .selected = true;'value =Change option to 2/>
不幸的是,您需要手动触发更改
事件。而事件构造器将是最好的解决方案。
< select id = selonchange ='alert(changed)'> < option value ='1'>一个< / option> < option value ='2'>两个< / option> < / select>< input type =buttonvalue =将选项更改为2/>
$ p 当然,IE不支持Event构造函数。所以你可能需要用这个来填充:
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;
}
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?
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" />
Unfortunately, you need to manually fire change
event. And Event Contructor 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" />
And of course, Event constructor is not supported on 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;
}
这篇关于更改< select>的选项并使用JavaScript触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!