取消绑定点击div。我有两个div。我想将click事件解除绑定到内部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>
答案 0 :(得分:2)
确保在注册click事件后调用unbind函数,而不是之前。如果在解除绑定后注册了click事件,则不会删除click事件。
$(".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()
。
答案 1 :(得分: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
});
答案 2 :(得分:0)
您可以使用:
$('.triangles').on("click", function() {
alert('something');
});
$('.triangles').off("click");