How to stop default link click behavior with jQuer

2019-01-04 11:44发布

I have a link on a webpage. 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?

5条回答
Evening l夕情丶
2楼-- · 2019-01-04 12:13

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

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-04 12:14
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.

查看更多
放我归山
4楼-- · 2019-01-04 12:15

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.

查看更多
太酷不给撩
5楼-- · 2019-01-04 12:17
$('.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.

查看更多
爷的心禁止访问
6楼-- · 2019-01-04 12:39

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);  
查看更多
登录 后发表回答