javascript 如何禁用或隐藏超链接的“在新标签页中打开”选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17169198/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:20:54  来源:igfitidea点击:

How to disable or hide the Open In New Tab option for hyperlinks

javascript

提问by Ashish Arora

On hyperlinks in the right click menu, how can I remove or hide the Open In New Taband Open In New Windowoptions?

在右键菜单中的超链接上,如何删除或隐藏在新选项卡中打开在新窗口中打开选项?

for example

例如

<a href="#" onclick="asd">foo</a>

回答by MrCode

Not sure why you'd want to do this but it can be done by moving the hrefto a data-hrefattribute, then remove the hrefand add a click handler. The onclick will read the data-hrefand redirect.

不确定为什么要这样做,但可以通过将 移动hrefdata-href属性来完成,然后删除href并添加点击处理程序。onclick 将读取data-href并重定向。

Demo

演示

var links = document.getElementsByTagName("a");

for(var i=0; i<links.length; i++){
    links[i].setAttribute("data-href", links[i].getAttribute("href"));
    links[i].removeAttribute("href");
    links[i].onclick = function(){
        window.location = this.getAttribute("data-href");
    };
}

The right click menu shows:

右键菜单显示:

enter image description here

在此处输入图片说明

回答by tornados

You can use javascript link instead of plain html ones. Just do href="javascript:void(0)" and handle the click event to redirect the page. This won't remove the option of opening in another tab but will make sure the page doesn't actually open up when tried.

您可以使用 javascript 链接而不是纯 html 链接。只需执行 href="javascript:void(0)" 并处理点击事件以重定向页面。这不会删除在另一个选项卡中打开的选项,但会确保页面在尝试时实际上不会打开。

Also instead of an HTML tag, you can instead use another tag like and give it a cursor:pointer css property and jquery onclick to make it work like a link. This will completely remove the option "open in another tab" from context menu.

此外,除了 HTML 标签之外,您还可以使用另一个标签,例如并给它一个 cursor:pointer css 属性和 jquery onclick 以使其像链接一样工作。这将从上下文菜单中完全删除“在另一个选项卡中打开”选项。

回答by Anand Shah

you can do it using following code.

您可以使用以下代码来完成。

<script language="javascript">
$("a").click(function(event)
{
  if(event.button==2)
   {
     return false;    
   }
});
</script>