使用javascript / jquery打开新背景选项卡中的链接

问题描述:

我希望功能在用户点击链接时默认打开网站中的所有链接到新的背景标签。我已经检查了所有,但没有一个提供适用于所有浏览器的解决方案。我已经提到以下两个链接来编写我的代码:

I want the functionality to open all links in a website to a new background tab by default when a user clicks on the link. I have checked all over but none of them provide a solution that works on all browsers. I have referred the following two links to write my code:

Working example in chrome

建议修改ie

我有以下代码:

<html>
<head>
<style type="text/css">
.link{ color: #0055ff; cursor: pointer; text-decoration: underline; }
</style>


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".link").on('click', function(event){
var $this = $(this);
    var a = document.createElement("a");

    a.href = $this.href;


    if( document.createEvent ) {
        var evObj = document.createEvent('MouseEvents');
        evObj.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                            true, false, false, true, 1, a);
        a.dispatchEvent( evObj );

    } else if( document.createEventObject ) {
        var evObj = document.createEventObject();
        evObj.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                            true, false, false, true, 1, a);
        a.fireEvent( 'onclick', evObj );
    }
});
});
</script>
</head>
<body>
<span class="link" data-href="http://www.google.com">Go to Google</span>
</body>
</html>


jQuery(将被弹出窗口拦截器阻止)

jQuery (will be stopped by popup blockers)

<html>
<head>
<style type="text/css">
.link{ color: #0055ff; cursor: pointer; text-decoration: underline; }
</style>


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".link").on('click', function(event){
var $this = $(this);

    window.open($this.href, '_blank');

});
});
</script>
</head>
<body>
<span class="link" data-href="http://www.google.com">Go to Google</span>
</body>
</html>

Javascript(不会被弹出窗口拦截器阻止)

Javascript (will NOT be stopped by popup blockers)

<html>
<head>
<style type="text/css">
.link{ color: #0055ff; cursor: pointer; text-decoration: underline; }
</style>
</head>
<body>
<span class="link" onclick="window.open('http://www.google.com', '_blank')">Go to Google</span>
</body>
</html>

根据问题主题发表评论:

A comment though, based on the topic of the question:

人们可以选择他们的浏览器应该如何操作,这对我们的开发人员来说不应该覆盖...更好的方法是为他们提供一种方式,通过询问他们是否想要以新的方式打开选项卡/窗口或不首先......其次,告诉他们为什么他们应该按照您的喜好以及在您的网站上这样做的好处。这可能会让你到达你想要的地方

People make a choice how their browser should act and it's not meant for us developers to override that... a much better approach would be to offer them a way, by asking if they want to open in a new tab/window or not in the first place... and secondly, to inform them of why they should do as you like and the benefits of doing so on your site. That might get you where you want