简体   繁体   English

从元素取消绑定jQuery click事件

[英]Unbind jQuery click event from the element

All the elements with .btn class are bound to a jQuery click event on page load. 具有.btn类的所有元素在页面加载时都绑定到jQuery click事件。 Is there a way to unbind a single element that uses the class .btn . 有没有一种方法可以解除绑定使用类.btn的单个元素。 I tried by adding return false in the onclick event to an anchor tag like this 我尝试通过将onclick事件中的return false添加到这样的锚标记中

<a href="index.html" class="btn" onclick="return false;" target="_blank">Link</a>

but it doesn't seem to override or prevent it from performing the click event bound by jQuery 但它似乎并未覆盖或阻止它执行jQuery绑定的click事件

EDIT 编辑
Thanks for all the answers, but is there an inline solution to this? 感谢您提供所有答案,但是对此有内联解决方案吗? Something like onclick="event.preventDefault();" 类似于onclick="event.preventDefault();"

Also follow up question: Just curious, which among onclick and jQuery event listener gets called first? 还跟进问题:只是好奇,在onclickjQuery事件监听器中哪个首先被调用?

Use unbind() method of Jquery. 使用Jquery的unbind()方法。

<a href="index.html" onclick="return false;" target="_blank" id="xyz">Link</a>      

$(document).ready(function(){
     $("#xyz").unbind("click");
});

You can use jquery .not to narrow the selection with a specific button where you need to give this button a unique id: 您可以使用jquery .not通过特定按钮来缩小选择范围,在此您需要为该按钮赋予唯一的ID:

<a href="index.html" class="btn" id="prevent" target="_blank">Link</a>
<a href="index.html" class="btn"  target="_blank">Link</a>

$(".btn").not("#prevent").click(function(){

});

If you added event click via delegation like this : 如果您添加了事件,则通过如下所示的委托单击

$(document).on('click', '.btn', function(e){});

You must stop event propagation from your own .btn 您必须停止从自己的.btn传播事件

$('.myOwnBtn').on('click', function(e) {
    e.preventDefault();
});

How do you add event click on your .btn ? 如何在.btn上添加事件点击? If you add event by click, you can off it 如果您单击添加事件,则可以将其关闭

$('.myOwnBtn').off('click');

Onclick attribute is executed before click event from jquery and is completely independent from click event from jquery. Onclick属性在jquery的click事件之前执行,并且完全独立于jquery的click事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM