在执行 .off() 后如何使用 .on() 重新绑定 jQuery 事件

3

我有一个.on('click', 'td', function(){})事件。 我将其关闭.off('click', 'td')。现在我想再次绑定同样的事件.on()。我尝试了一些.on()的组合,但是没有成功。可能需要将其分配给一个变量,但不确定如何做。


1
我无法复制这个问题。 (http://jsfiddle.net/UcHj9/) - Ohgodwhy
我必须重新定义整个函数吗?我想使用之前定义过的.on() 事件。可以通过将其分配给变量来实现,但不确定如何做到这一点。 - change
2个回答

8
将事件处理函数放在一个变量中,并像这样使用它:

将事件处理函数放入变量中,然后像下面这样使用:

var handler = function(e){
    //code here
}

//on
$('#myselector').on('click', handler);

//off
//Try this, this will only turn 'handler' off
$('#myselector').off('click', handler);

//If the above doesn't work, then try this
//This will turn off all your other click handlers for the same element,
//if for some reason turning off a particular handler doesn't work!
$('#myselector').off('click');

//on again
$('#myselector').on('click', handler);

4

我假设您希望点击TD时会发生以下情况:首先给您的td添加一个类来表明它是开启还是关闭状态。默认情况下,TD将具有td-off类,如下所示:

<td class="td-off">

然后设置一个事件来更改类。
.on('click','td',function(){

  if($(this).hasClass('td-off')){
    $(this).removeClass('td-off');
    $(this).addClass('td-on');
  }else{
    $(this).removeClass('td-on');
    $(this).addClass('td-off');
  }

});

然后最后设置你的开启或关闭事件。
$('.td-on').click(function(){
    //Your event on
});

$('.td-off').click(function(){
   //Your event off
});

这可能不是最好的答案,但我希望你能理解


不知道为什么我没想到。让我试一下,应该可以。 - change

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接