html - 如何防止浏览器打开href中指定的链接? [英] html - How to prevent the browser from opening the link specified in href?

查看:132
本文介绍了html - 如何防止浏览器打开href中指定的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在制作一个文件浏览器。如果用户点击某个文件的链接,打开一个小窗口并要求提供选项(如下载和查看)。我已经使用onclick属性完成了此操作。如果我点击链接的JavaScript执行,但在此之后在href中指定的网址打开。我想要做的是:如果你点击链接JavaScript执行并最终转发给你。但是,如果链接被右键点击,复制链接位置应该仍然可用。
我想通过阻止转发脚本来解决这个问题。因此,如果链接被右键单击,则不执行JavaScript,并且您可以复制链接位置。但是,如果您点击链接,JavaScript将被执行并且链接不会打开。
这是可能的JavaScript,或者是否有任何其他方式来实现此行为?

解决方案

为了防止链接执行,一种方法是让onclick方法返回 false



例如: p>

 < a href =http:// ...onclick =return clickfunc()> ...< ; / A> 

如果 clickfunc()返回 false ,链接上的点击不会直接指向http:// ...。

尽管您可能正在处理它更像是

 < a href =http:// ...id =somebutton> .. < / A> 
< script>
document.getElementById('somebutton')。onclick = function(){
...
else {return false; }
};
< / script>


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?

解决方案

In order to prevent the link executing, one way is to let the "onclick" method return false.

For example:

<a href="http://..." onclick="return clickfunc()">...</a>

If clickfunc() returns false, a click on the link will not direct to "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>

这篇关于html - 如何防止浏览器打开href中指定的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆