Javascript jQuery 为传出链接添加 target="_blank"

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

jQuery add target="_blank" for outgoing link

javascriptjquery

提问by GusDeCooL

I need some help to create jquery script :)
I have some of link like this on my HTML.

我需要一些帮助来创建 jquery 脚本 :)
我的 HTML 上有一些这样的链接。

<a href="http://google.com">Google</a>
<a href="/">Home</a>
<a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a>

And now i want jQuery to check all of the link on my page. if that link is outside of my server (my server is gusdecool.com). Then add target="_blank". and the result will be like this

现在我想让 jQuery 检查我页面上的所有链接。如果该链接在我的服务器之外(我的服务器是gusdecool.com)。然后添加target="_blank". 结果会是这样

<a href="http://google.com" target="_blank">Google</a>
<a href="/">Home</a>
<a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a>

回答by Moin Zaman

assuming that all external links will start with http://you could do this:

假设所有外部链接都以http://开头,您可以这样做:

$('a[href^="http://"]').not('a[href*=gusdecool]').attr('target','_blank');

$('a[href^="http://"]').not('a[href*=gusdecool]').attr('target','_blank');

回答by Ryan Doom

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
      $(this).attr("target","_blank");
   }
});

This was from css-tricks.com, seems to work pretty well.

这是来自 css-tricks.com,似乎工作得很好。

回答by gion_13

$('a[href^=http]:not([href^=http://www.gusdecool.com/])').attr('target','_blank');

Of course, this works only if all the external links start with the http protocol. You should adapt this code to suite your needs (suchs as links without protocols, or with different protocols).

当然,这只有在所有外部链接都以 http 协议开头时才有效。您应该调整此代码以满足您的需求(例如没有协议的链接,或具有不同协议的链接)。

UPDATE :

更新 :

$('a[href^=http]:not([href^=http://www.gusdecool.com],[href^=http://gusdecool.com])')
    .add('a[href^=www]:not([href^=www.gusdecool.com])')
        .attr('target','_blank');

It selects all the aelements that have their hrefattribute starting with a web page address (with or without protocol) and do not point to your site's address and changes their targetattribute to _blank.

它选择所有属性以网页地址(有或没有协议)开头且不指向您网站地址的a元素,href并将其target属性更改为_blank.

回答by Guyom

This function seems to be easier if you have a subdomain:

如果您有子域,此功能似乎更容易:

$('a').attr('target', function() {
  if(this.host == location.host) return '_self'
  else return '_blank'
});

回答by Pedro Paulo Cintra Dias

Global function to open external links in a new window:

在新窗口中打开外部链接的全局函数:

$(function(){ // document ready

    $("a").filter(function () {
        return this.hostname && this.hostname !== location.hostname;
    }).each(function () {
        $(this).attr({
            target: "_blank",
            title: "Visit " + this.href + " (click to open in a new window)"
        });
    });

});

回答by Hendriono

jQuery(document).ready(function(){
    target_luar();
});    
function target_luar(){
    try{
        if(top.location != location) {
            jQuery("a[href^='http']")
              .not("[href*='"+location.host+"']")
              .attr('target','_blank');
        }
    } catch(err) { }
}

Demo : Demo jQuery External Link

演示:演示 jQuery 外部链接

回答by boateng

Putting it all together we get the following.. Wait for it all to load, select only links starting with http or https, check if the link point to the same domain (internal) or another domain (external), add appropriate target if match found..

将它们放在一起,我们得到以下内容.. 等待全部加载,仅选择以 http 或 https 开头的链接,检查链接是否指向同一个域(内部)或另一个域(外部),如果匹配则添加适当的目标成立..

$(window).load(function() {
    $('a[href^="http"]').attr('target', function() {
      if(this.host == location.host) return '_self'
      else return '_blank'
    });
});

回答by Shai Mishali

You could use jQuery's $.each function to iterate over all Anchor tags, perform the needed check and set the "target" attribute using $(this).attr("target","_blank");

您可以使用 jQuery 的 $.each 函数遍历所有 Anchor 标签,执行所需的检查并使用 $(this).attr("target","_blank"); 设置“target”属性;

Example (Not tested but should work):

示例(未测试但应该可以工作):

$('a').each(function(index) {
    var link = $(this).attr("href");
    if(link.substring(0,7) == "http://")
        $(this).attr("target", "_blank");
});

Shai.

谢。

回答by Kaya M

This is such a brilliant site I learned so much from it :

这是一个如此出色的网站,我从中学到了很多东西:

If you do it this way you do not need to worry about http or https (handy while developing)

如果你这样做,你就不需要担心 http 或 https(开发时很方便)

$('a[href^="http"]')
        .not('a[href*='+ location.hostname +']')
        .attr('target','_blank');

回答by user2394268

Try:

尝试:

$('a[href^="http://"]')
        .not('a[href*='+ location.hostname +']')
        .attr('target','_blank');