Javascript html - 如何防止浏览器打开 href 中指定的链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10219073/
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
html - How to prevent the browser from opening the link specified in href?
提问by jangxx
I currently making a filebrowser. If the user clicks on a link to a file a little window open and asks for options (like download and view). I've done this using the onclick attribute. If I click on the link the javascript is executed, but after this the url specified in href opens. What I'm trying to do is: If you click the link javascript get executed and forwards you eventually. But if the link gets rightclicked the "copy link location" should still be available. I'm thinking of solving this by blocking the forwarding scriptside. So if the link gets rightclicked no javascript is executed and you can copy the link location. But if you left click the link the javascript is executed and the link is not opened. Is that possible with javascript, or is there any other way of achieving this behavior?
我目前正在制作一个文件浏览器。如果用户单击文件链接,则会打开一个小窗口并询问选项(如下载和查看)。我已经使用 onclick 属性完成了此操作。如果我单击链接,则执行 javascript,但在此之后,href 中指定的 url 将打开。我想要做的是:如果您单击链接,javascript 将被执行并最终转发给您。但是如果链接被右键单击,“复制链接位置”应该仍然可用。我正在考虑通过阻止转发脚本来解决这个问题。因此,如果链接被右键单击,则不会执行 javascript,您可以复制链接位置。但是,如果您左键单击该链接,则会执行 javascript 并且不会打开该链接。javascript可以做到这一点,还是有其他方法可以实现这种行为?
回答by Armatus
In order to prevent the link executing, one way is to let the "onclick" method return false
.
为了防止链接执行,一种方法是让“onclick”方法返回false
。
For example:
例如:
<a href="http://..." onclick="return clickfunc()">...</a>
If clickfunc()
returns false
, a click on the link will not direct to "http://..."
如果clickfunc()
返回false
,点击链接不会直接到“http://...”
Although you are probably handling it more like
虽然你可能更喜欢处理它
<a href="http://..." id="somebutton">...</a>
<script>
document.getElementById('somebutton').onclick = function() {
...
else { return false; }
};
</script>
回答by bobek
You have to prevent default from your click function:
您必须防止点击功能的默认值:
function stopDefAction(evt) {
evt.preventDefault();
}
回答by lexa-b
you can replace href attribute by text "javascript:void(0)", for example:
您可以用文本“javascript:void(0)”替换 href 属性,例如:
<a href="http://..." id="somebutton">...</a>
<script>
document.getElementById('somebutton').href="javascript:void(0)"
</script>
回答by Bergi
Yes, you will need to prevent the default actionof the event. You can do so by returning false
in your onclick attribute.