单击其他div标签时,在运行时覆盖单击绑定

时间:2015-05-06 21:33:49

标签: javascript jquery

我打算在运行时覆盖一些功能。所以我想要的是首先取消绑定并再次绑定。这是有效的,但我想知道它是如何工作的。例如,我做了如下。如果我愿意,这是在运行时覆盖的正确方法吗?

$('#test').bind('click', function (event) {
    alert("hello");
});  

$('#test2').bind('click', function (event) {

    alert("test again");

    $('#test').unbind();

    $('#test').bind('click', function (event) {
        alert("hey test");
    });
});

这是 JSFiddle

2 个答案:

答案 0 :(得分:1)

是的,这是正确的方法,但您应该使用jQuery webDriver.Quit(); 作为附加/分离事件处理程序。来自jQuery文档(http://api.jquery.com/bind/):

  

从jQuery 1.7开始,.on()方法是将事件处理程序附加到文档的首选方法。

http://api.jquery.com/on/

http://api.jquery.com/off/

on/off

https://jsfiddle.net/sergdenisov/rqqzvwak/3/

答案 1 :(得分:0)

  

在最简单的情况下,没有参数,.unbind()会删除所有参数   附加到元素的处理程序

通过遵循以下模式,您的代码可以改进,以减少错误:

var testClicked = function (event) {
    alert("hello");
};
var neverSayDie = function(event){
    alert("'hello' is gone, but I'm still here!");
};

$('#test').bind('click', testClicked);
$('#test').bind('click', neverSayDie);

$('#test2').bind('click', function (event) {

    alert("test again");

    // only the click event registered to be handled
    // by testClick function will be unregistered 
    $('#test').unbind("click", testClicked);

    $('#test').bind('click', function (event) {
        alert("hey govind");
    });
});

这是你的fiddle updated

是否使用 bind / unbind 开/关,这是一个完全不同的问题。 JQuery 建议 开启/关闭,但如果绑定/取消绑定请更多,嘿,享受吧!