javascript 单击超链接后如何防止重定向?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26474292/
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
How to prevent redirect after hyperlink click?
提问by gstackoverflow
I have following html+ js code:
我有以下 html+ js 代码:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<a href="#" id=key onclick="func(0)">foo</a>
</body>
<script type="text/javascript">
function func(k){
alert(1);
return false;
}
</script>
</html>
Can you explain how to refactor following code that after click on href code func
executes but # doesn't add to the URL and page shouldn't be reload?
你能解释一下如何重构以下代码,在点击 href 代码后func
执行但 # 不添加到 URL 并且页面不应该重新加载吗?
回答by webeno
Use javascript:void(0);
instead of #
as follows:
使用javascript:void(0);
代替#
如下:
<a href="javascript:void(0);" id=key onclick="func(0)">foo</a>
回答by Ben Hull
You can simply remove the href attribute:
您可以简单地删除 href 属性:
<a id='key' onclick="func(0)">foo</a>
回答by qwertymk
Change it to:
将其更改为:
vvvvvvv
<a href="#" id=key onclick="return func(0)">foo</a>
回答by Sergio Toledo Piza
I think you forgot the quotation marks in "key"
我想你忘记了“key”中的引号
<a href="#" id="key" onclick="func(0)">foo</a>
<a href="#" id="key" onclick="func(0)">foo</a>
回答by nickspiel
To be more semantically correct I would be using a button with the following onclick:
为了在语义上更正确,我将使用带有以下 onclick 的按钮:
<button id=key onclick="return func(0)">foo</button>
This way there is no need to hack around with e.preventDefault / return false.
这样就不需要修改 e.preventDefault / return false。