解除绑定点击在使用直播时不起作用

时间:2013-06-05 11:16:41

标签: jquery click

对于某些html元素,我需要使用unbind或off函数删除其他点击功能

但是这个功能只适用于点击功能 如下:

 $("#test").click(function(){
  alert("test1");
  });
  $("#test").unbind('click').click(function(){ // or off
   alert("test2");
  });

但是使用直播,这不起作用,并且会触发两个警报

 $("#test").live('click',function(){
  alert("test1");
  });
  $("#test").off('click').click(function(){ //unbind
   alert("test2");
  });

4 个答案:

答案 0 :(得分:4)

.live()相反的是.die()http://api.jquery.com/die/

$("#test").die('click').click(function(){ //unbind
  alert("test2");
});

BTW:.live()自1.7以来已被弃用。但是如果你使用旧版本的jQuery,我发现使用它没有问题。

答案 1 :(得分:3)

 $(document).on('click','#test',function(){
  alert("test1");
  });

答案 2 :(得分:3)

不要使用.live(),因为它已被弃用。

改为使用.on()

$(document).on('click', '#test', function () {

此外,.off()仅取消绑定与.on()绑定的事件处理程序。有关详细信息,请参阅documentation

答案 3 :(得分:1)

从jQuery 1.7开始,不推荐使用.live()方法。使用.on()附加事件处理程序。

请记住offon一起使用,dielive一起使用

相关问题