如何停止默认的链接点击行为与 jQuery

我在一个网页上有一个链接。当用户单击它时,页面上的小部件应该更新。但是,我正在做一些事情,因为默认功能(导航到不同的页面)发生在事件触发之前。

这是链接的样子:

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

下面是 jQuery 的样子:

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

有什么问题吗?

153171 次浏览
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.

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.

$('.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.

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

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);

I've just wasted an hour on this. I tried everything - it turned out (and I can hardly believe this) that giving my cancel button and element id of cancel meant that any attempt to prevent event propagation would fail! I guess an HTML page must treat this as someone pressing ESC?