jQuery click(false) 与函数结合
我想防止使用“#”,因为我正在使用 jQuery 通过单击插件执行其他操作...
<a href="#" id="mylink">My Link</a>
<script>
$('#mylink').somePlugin().click(false);
</script>
每当我需要阻止默认单击时,上面的方法都可以很好地工作。
现在我有如下类似的内容,我想阻止默认的点击行为,
<a href="#" id="mylink">My Link</a>
$('#mylink').click( function () {
// my code in here
});
我只是不确定在哪里/如何将 click(false) 合并到上面的代码中。我尝试过的几件事都不起作用。
我知道...我感觉自己像个新手问这个问题。
谢谢你!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你需要做:
You need to do:
不同的浏览器处理此问题的方式略有不同,但 jQuery 会尽力满足您的需求。您应该了解三件事,并且至少应该完成前两件事,以防止在尽可能多的浏览器中出现正常点击行为:
return false;
在您的代码末尾点击处理程序(如建议的)将停止常规点击许多浏览器(包括 Internet Explorer 和 Google Chrome)中对链接的操作。return false;
也会停止事件传播,这可能是也可能不是您想要的。这是常规的浏览器行为,与 jQuery 没有任何关系。e.preventDefault();
,如jQuery 方法,它可以防止默认操作被触发。 “例如,单击的锚点不会将浏览器带到新的 URL。” 这仅影响当前项目。e.stopPropagation();
是另一个 jQuery 方法 防止事件冒泡。例如,如果 div 中有一个锚点,并且该 div 有一个挂钩的单击事件,则即使您停止锚点,该 div 的单击事件也会被触发 - 除非您调用此方法。数字 2 将涵盖几乎所有浏览器,通过结合 1 和 2,您或多或少地涵盖了所有浏览器。仅当您不希望事件在 DOM 树中冒泡时,数字 3 才是必需的,但我习惯将其放在那里,因为大多数情况下,如果我想阻止对单击的元素执行默认操作,我不会这样做希望除了此特定处理程序中的代码之外的任何事情发生。
Different browsers handle this in slightly different ways, but jQuery does its best to cover your bases. There are three things you should know about, and at least the first two of them should be done to prevent normal click behavior in as many browsers as possible:
return false;
at the end of your click handler (as Am suggested) will stop the regular click action on a link in many browsers, including Internet Explorer and Google Chrome.return false;
will also stop event propagation, which may or may not be what you wish. This is regular browser behavior, and does not have anything to do with jQuery.e.preventDefault();
, as suggested by Liam is a jQuery method that prevents the default action to be triggered. "For example, clicked anchors will not take the browser to a new URL." This affects only the current item.e.stopPropagation();
is another jQuery method that prevents an event from bubbling. For example, if you have an anchor in a div, and the div has a click event hooked to it, the div's click event will be triggered even though you stop the anchors - unless you call this method.Number 2 will cover almost all browsers, and with a combination of 1 and 2 you cover more or less all of them. Number 3 is only necessary if you don't want the event to bubble in the DOM tree, but I make it a habit to have it there, since mostly if I want to prevent the default action on a clicked element, I don't want anything except the code in this specific handler to happen.