Javascript 防止锚行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4387580/
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
Prevent anchor behaviour
提问by Nick
When I want to prevent default behaviour of anchor tag I`m using
当我想阻止我使用的锚标记的默认行为时
<a href="javascript:void(0);">link</a>
Which is the most effective solution ?
哪个是最有效的解决方案?
采纳答案by karim79
An example of a gracefully degrading solution:
优雅降级解决方案的示例:
<a href="no-script.html" id="myLink">link</a>
<script>
document.getElementById("myLink").onclick = function() {
// do things, and then
return false;
};
</script>
回答by Charles Ouellet
This is a nice approach, if you're using jquery you can also do:
这是一个不错的方法,如果您使用 jquery,您还可以这样做:
<a id="link" href="javascript:void(0)">link</a>
<script type="text/javascript">
$("#link").click(function(ev) {
ev.preventDefault();
});
</script>
preventDefault can be useful also to prevent submitting form
preventDefault 也可用于防止提交表单
回答by Shadow Wizard is Ear For You
You can also have this:
你也可以有这个:
<a href="#" onclick="return false;">link</a>
回答by dxh
If you never want for the browser to follow the link anywhere, I'd say what you've got is the simplest, safest solution.
如果您从不希望浏览器在任何地方跟随链接,我会说您拥有的是最简单、最安全的解决方案。
Sure, there are heaps of other solutions you could apply with javascript, but most other ways may fail when
当然,您可以使用 javascript 应用许多其他解决方案,但大多数其他方法可能会失败
- The DOM is not completely loaded, if the event is assigned at DOMReady or later, which is common.
- A click event listener handles the link (which is common where you want links not to be followed by the browser). If an error occurs in the javascript that handles the click, the
return false;
orpreventDefault
that might be at the end of the statement, will not be executed, and the browser will follow the link, if only to#
.
- 如果事件在 DOMReady 或之后分配,则 DOM 未完全加载,这很常见。
- 单击事件侦听器处理链接(这在您希望浏览器不跟随链接的情况下很常见)。如果在处理点击的 javascript 中发生错误,则可能在语句末尾的
return false;
或preventDefault
将不会被执行,并且浏览器将跟随链接,如果只是到#
.
回答by Musarrof
Here is very easy way to stop this.
这是阻止这种情况的非常简单的方法。
( function( $ ) {
$( 'a[href="#"]' ).click( function(e) {
e.preventDefault();
} );
} )( jQuery );
回答by ankit suthar
I know it's an old thread but here is what I use often
我知道这是一个旧线程,但这是我经常使用的
Instead of this:
取而代之的是:
<a href="javascript:void(0);">link</a>
<a href="javascript:void(0);">link</a>
This also can work:
这也可以工作:
<a href="javascript:;">link</a>
<a href="javascript:;">link</a>