2

取消绑定单击到 div。我有两个 div。我想将点击事件解除绑定到内部 div

加载页面时,我想将点击事件解除绑定到triangle. 我的 JQuery 代码:

 $(".wrapper").unbind();
 $(".triangles").unbind();

 $(".triangles" ).click(function(){   //it is still clickable

  alert("hello u clicked me");
 });

<div class="wrapper">
     <div class="triangles">
     </div>
     <div class="triangles">
     </div>
     <div class="triangles">
     </div>
</div>
4

3 回答 3

2

确保在注册 click 事件之后调用 unbind 函数,而不是之前。如果解除绑定后注册了点击事件,那么点击事件不会被移除。

$(".triangles" ).click(function(){   //it is still clickable

    alert("hello u clicked me");
});

// this will remove the click event and all other handlers 
$(".wrapper").unbind();
$(".triangles").unbind();

另外,我想指出您的代码中的语法错误。您的 click 事件处理程序缺少);关闭它所需的处理程序。

如果您要经常删除并重新应用单击事件,则可能需要将其包装在另一个函数中:

function bindClick() {
    $(".triangles" ).click(function(){   //it is still clickable

        alert("hello u clicked me");
    });
}

现在您可以bindClick()在需要重新应用点击事件时调用。

于 2012-05-06T06:49:55.083 回答
2

用于.off()在需要时取消绑定事件。

例子:

$(".triangles").off("click");

另一个例子:这里它第一次可以点击,第二次不能点击

$(".triangles" ).click(function(){
    alert("hello u clicked me");
    $(this).off('click'); //after this, $(".triangles") will not longer be clickable
});

试试看 :)


让我解释一下,你在代码中做错了什么

 $(".wrapper").unbind(); //unbinded all the events
 $(".triangles").unbind();  //unbinded all the events

 $(".triangles" ).click(function(){  //binded another click event
     alert("hello u clicked me"); //So of course it will be clickable
 });
于 2012-05-06T06:53:48.767 回答
0

您可以使用:

$('.triangles').on("click", function() {
    alert('something');
});

$('.triangles').off("click");
于 2012-05-06T06:54:42.217 回答