How to stop default link click behavior with jQuery

两盒软妹~` 提交于 2019-12-17 04:00:46

问题


I have a link on a web page. When a user clicks it, a widget on the page should update. However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.

This is what the link looks like:

  <a href="store/cart/" class="update-cart">Update Cart</a>

This is what the jQuery looks like:

   $('.update-cart').click(function(e) { 
         e.stopPropagation(); 
         updateCartWidget(); 
      });

What is the problem?


回答1:


e.preventDefault();

from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Cancels the event if it is cancelable, without stopping further propagation of the event.




回答2:


You want e.preventDefault() to prevent the default functionality from occurring.

Or have return false from your method.

preventDefault prevents the default functionality and stopPropagation prevents the event from bubbling up to container elements.




回答3:


$('.update-cart').click(function(e) {
    updateCartWidget();
    e.stopPropagation();
    e.preventDefault();
});

$('.update-cart').click(function() {
    updateCartWidget();
    return false;
});

The following methods achieve the exact same thing.




回答4:


You can use e.preventDefault(); instead of e.stopPropagation();




回答5:


This code strip all event listeners

var old_element=document.getElementsByClassName(".update-cart");    
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);  


来源:https://stackoverflow.com/questions/5632031/how-to-stop-default-link-click-behavior-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!