如何使用.on / off重新绑定按钮的单击事件

时间:2013-08-06 08:44:05

标签: javascript jquery

对于绑定和取消绑定事件处理程序,我正在使用 on()/ off()事件处理程序附件。

HTML:

<div id='load' class="UnfiledContainer">
    <button onclick="loaded()">Try it</button>
    <p id="demo"></p>
</div>

JS:

$('#sync_img').on('click', function () {
    alert("Sync");
});

loaded = function () {
    $('#sync_img').off('click');  //Works perfectly
    var x = "";
    for (var i = 0; i < 100; i++) {
        x = x + "Thenumberis" + i;
    }
    document.getElementById("demo").innerHTML = x;
    $('#sync_img').on('click');   // This is not rebinding the click event
}

当用户点击#sync_img时,我会显示提醒。鉴于#load时,我使用 .off()解除了#sync_img的点击事件的绑定。

我尝试使用 .on()重新绑定它,但我无法重新绑定它。

以下是JSFiddle

请分享您的建议。

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

如果要重新绑定事件,则需要再次再次指定eventHandler

 // Bind the event
   $('#sync_img').on('click', clickEvent); 

   // Remove the handler
   $('#sync_img').off('click'); 

   // Need to rebind the event passing in the handler again
    $('#sync_img').on('click', clickEvent); 

    function clickEvent() {
       alert("Sync");
    }

否则它不知道它必须绑定到哪个处理程序。

因为您可以将多个hanlders绑定到单个事件。

$('#sync_img').on('click', clickEvent1);
$('#sync_img').on('click', clickEvent2); 

因此,当您想解除所有点击事件的绑定时。您将使用

$('#sync_img').off('click'); 

但是,如果您只想取消绑定单个事件,那么您只需传入要删除的处理程序

$('#sync_img').off('click', clickEvent1); 

这只删除了第一个处理程序。但是另一个处理程序仍然会触发,因为只删除了第一个处理程序。

<强> Unbind All handlers

<强> Unbind a specific handler