javascript 选择输入事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7038282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript select input event
提问by Bogdan
I'm trying to create a select input from javascript and bind a function to when a user changes an option. So far I have:
我正在尝试从 javascript 创建一个选择输入,并在用户更改选项时绑定一个函数。到目前为止,我有:
filter.change = function() {
console.log("CHANGED");
}
But nothing happens on selecting something else. What is wrong with this code. Also, how can I get the new selected value in the function ? Something like:
但是在选择其他东西时没有任何反应。这段代码有什么问题。另外,如何在函数中获取新的选定值?就像是:
console.log(this.value + "has been selected")
回答by Digital Plane
You were close, you need to use onchange
:
你很接近,你需要使用onchange
:
filter.onchange = function() {
alert("CHANGED");
//You can alert the value of the selected option, using this:
alert(this.value + " was selected");
}
Of course as Delan said, you should addEventListener
(and attachEvent
) whenever possible. Example:
当然,正如德兰所说,你应该addEventListener
(和attachEvent
)尽可能。例子:
//Define a onchange handler:
var changeHandler = function() {
alert("CHANGED");
//You can alert the value of the selected option, using this:
alert(this.value + " was selected");
}
//First try using addEventListener, the standard method to add a event listener:
if(filter.addEventListener)
filter.addEventListener("change", changeHandler, false);
//If it doesn't exist, try attachEvent, the IE way:
else if(filter.attachEvent)
filter.attachEvent("onchange", changeHandler);
//Just use onchange if neither exist
else
filter.onchange = changeHandler;
回答by Felix Kling
If you use this way, the property name is onchange
:
如果使用这种方式,则属性名称为onchange
:
filter.onchange = function() {
alert(this.value + "has been selected");
};
Further information:
更多信息:
Note:There is also another way to register event handlers, which allows to assign multiple event handlers for the same event. For more information, have a look at quirksmode.org - Advanced event registration models.
注意:还有另一种注册事件处理程序的方法,它允许为同一事件分配多个事件处理程序。有关更多信息,请查看quirksmode.org - 高级事件注册模型。