我在将 off()
和 on()
事件绑定(bind)到 select
下拉列表时遇到了这个奇怪的问题:
如果我取消绑定(bind)然后将 change
事件重新绑定(bind)到 select
下拉列表,我将无法更改下拉列表显示的值。换句话说,即使触发了更改事件,下拉列表中的所选值也不会正确更新。
如果我删除 off()
部分,只留下与 on()
绑定(bind)的事件,一切正常,但显然我无法阻止绑定(bind)同一事件多次发生。
在此处查看实例 http://jsfiddle.net/z7o11exs/
测试用例:
- 使用下拉列表(它有效!所选值正确显示在下拉列表中)
- 刷新页面。单击第一个按钮(关闭/打开),然后使用下拉菜单。由于所选值未更改,因此无法正常工作
- 刷新页面。单击第二个按钮(仅限),然后使用下拉菜单。它确实按预期工作。副作用:在第二个按钮上单击 n 次会将 n 次更改事件绑定(bind)到下拉元素
代码如下:
//--- This binds the event to the element
function bindEvent(){
$("#myselect").on("change", function(){
console.log("change");
});
}
//--- remove any change event previously added, then rebind it
function rebindEvent(){
$("#myselect").off("change").on("change", function(){
console.log("change");
});
}
提前致谢
最佳答案
尝试使用namespacing :
//--- This binds the event to the element
function bindEvent(){
$("#myselect").on("change.something", function(){
console.log("change");
});
}
//--- remove any change event previously added, then rebind it
function rebindEvent(){
$("#myselect").off("change.something").on("change", function(){
console.log("change");
});
}
正如@Karl所说,使用命名空间是:
为您的事件命名可以让您识别该事件。因此,在使用 .off 时,您可以针对特定事件进行关闭。
关于javascript - 如果更改事件未绑定(bind)然后反弹,下拉选项 "change"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28301358/