【问题标题】:How to rebind button's click event using .on/off如何使用 .on/off 重新绑定按钮的单击事件
【发布时间】:2013-08-06 17:01:14
【问题描述】:

对于绑定和取消绑定事件处理程序,我使用 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

请分享您的建议。

感谢任何帮助。

【问题讨论】:

  • $('#sync_img').on('click');你必须指定一个处理程序!
  • @roasted 而对于.off(),我没有指定处理程序。这会影响我的代码吗?
  • 不,检查文档。即使您应该使用命名空间的事件而不是原始事件

标签: javascript jquery


【解决方案1】:

如果要重新绑定事件,则需要再次指定 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");
    }

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

因为您可以将多个处理程序绑定到单个事件。

$('#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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多