Javascript 如何使用 jQuery 停止默认链接点击行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5632031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:10:10  来源:igfitidea点击:

How to stop default link click behavior with jQuery

javascriptjqueryeventsclickjquery-events

提问by smartcaveman

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:

这是 jQuery 的样子:

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

What is the problem?

问题是什么?

回答by Upvote

e.preventDefault();

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

来自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.

如果事件可取消,则取消事件,而不停止事件的进一步传播。

回答by Peeter

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

以下方法实现了完全相同的事情。

回答by Jonathon Bolster

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

您希望e.preventDefault()防止出现默认功能。

Or have return falsefrom your method.

或者return false从你的方法。

preventDefaultprevents the default functionality and stopPropagationprevents the event from bubbling up to container elements.

preventDefault阻止默认功能并stopPropagation阻止事件冒泡到容器元素。

回答by Null Pointer

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

您可以使用e.preventDefault();代替e.stopPropagation();

回答by Matoeil

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