javascript选择输入事件

时间:2011-08-12 09:40:18

标签: javascript

我正在尝试从javascript创建一个select输入,并将一个函数绑定到用户更改选项时。到目前为止,我有:

filter.change = function() {
    console.log("CHANGED");
}

但是在选择别的东西时没有任何反应。这段代码有什么问题。另外,如何在函数中获取新选择的值?类似的东西:

console.log(this.value + "has been selected")

3 个答案:

答案 0 :(得分:10)

你很接近,你需要使用onchange

filter.onchange = function() {
    alert("CHANGED");
    //You can alert the value of the selected option, using this:
    alert(this.value + " was selected");
}

当然,正如德兰所说,你应尽可能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;

答案 1 :(得分:5)

如果您使用这种方式,则属性名称为onchange

filter.onchange = function() {
     alert(this.value + "has been selected");
};

更多信息:

注意:还有另一种注册事件处理程序的方法,它允许为同一事件分配多个事件处理程序。有关详细信息,请查看quirksmode.org - Advanced event registration models

答案 2 :(得分:2)

如果您使用jQuery,则可以像这样使用

$('select').change(function(){
   alert($('select').val() + ' was just selected');
});

或使用.onchange

filter.onchange = function() {
    alert(this.value + " was selected");
}

而不是.change