【问题标题】:jQuery add target="_blank" for outgoing linkjQuery 为传出链接添加 target="_blank"
【发布时间】:2011-10-26 10:55:45
【问题描述】:

我需要一些帮助来创建 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>

现在我希望 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>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

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

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

【讨论】:

  • 不,请参阅我对 Joakim 的评论以获取解释:)
  • 外部站点仍可以仅以 www 开头,并且任何其他包含 gusdecool 关键字的链接(例如:http://sub.gusdecool.com 等子域)仍被视为外部站点到当前网页。
  • 我在搜索外部链接的快速解决方案后遇到了这个帖子,我认为选择器应该是 $('a[href^="http://"], a[href^="https://"]'). 以匹配 https 链接。
  • 这不包括 https 网站,你应该只使用$('a[href^="http"]').not('a[href*=gusdecool]').attr('target','_blank');
  • 我需要将“gusdecool”设置为单引号或双引号以使代码正常工作。
【解决方案2】:
$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
      $(this).attr("target","_blank");
   }
});

这是来自 css-tricks.com,看起来效果很好。

【讨论】:

  • 我有两个问题:1) 这是否适用于像&lt;a href="/"&gt;Home&lt;/a&gt; 这样的相对链接? 2) 你为什么不在循环前加上var a = new RegExp('/' + window.location.host + '/');
【解决方案3】:
$('a[href^=http]:not([href^=http://www.gusdecool.com/])').attr('target','_blank');

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

更新:

$('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');

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

【讨论】:

  • 不错的 jQuery 选择器!这应该在选定的正确答案之上投票,因为它是最好/最快的解决方案。
  • 您可能想添加"s?因为我得到了无法识别的表情。
  • 使用这些 jQuery 选择器会影响 javascript 性能。
【解决方案4】:

如果你有一个子域,这个功能似乎更容易:

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

【讨论】:

  • 这对我来说是最好的答案,因为完全不可知论(即不是硬写的东西)并且完全明确。 +1
【解决方案5】:
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 jQuery External Link

【讨论】:

    【解决方案6】:

    在新窗口中打开外部链接的全局功能:

    $(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)"
            });
        });
    
    });
    

    【讨论】:

    • 请注意(适用于本页的许多解决方案):如果您有一个 mailto 链接,它也会收到一个 target 属性,这可能会导致不良行为(在 Chrome 中,它可以工作,但也会打开一个额外的空白标签)。
    【解决方案7】:

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

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

    【讨论】:

    • 如果您能对您的代码提供一个简短的解释,那就太好了!
    【解决方案8】:

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

    示例(未测试但应该可以使用):

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

    夏。

    【讨论】:

      【解决方案9】:

      这是一个使用原始 JS(不是 jQuery)演示答案的小提琴:http://jsfiddle.net/Xwqmm/

      这是代码:

      var as = document.getElementsByTagName('a');
      var re = /^https?:\/\/([^\/]*)\//;
      for (var i = 0, l = as.length; i < l; i++) {
          var href = as[i].href;
          var matches = href.match(re);
          if (matches[1] && matches[1] != "gusdecool.com") {
              as[i].setAttribute("target","_blank");
          }
      }
      

      【讨论】:

        【解决方案10】:

        这是一个非常棒的网站,我从中学到了很多:

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

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

        【讨论】:

          【解决方案11】:

          你可以看到httphttps的所有外部链接

          
          jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").each(function() {
            
              console.log(jQuery(this).attr('href'))
          });
          
          

          你可以像这样添加_blank

          jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").attr('_target','blank');
          

          【讨论】:

            【解决方案12】:

            你可以使用filter -

            $("a").filter(function () {
                return this.indexOf('http://') > -1 && this.indexOf('gusdecool') == -1 
            }).attr("target","_blank");  
            

            【讨论】:

              【解决方案13】:

              检查每个链接对象 $(link).attr("href"),如果它以 http:// 开头,那么它是一个传出链接 (?)。然后分配 .attr("target", "_blank")。

              $(a).function(){
                  if($(this).attr("href").substring(0,3) == "http" && <!-- CHECK ITS NOT YOUR SITE URL -->){
                     $(this).attr("target", "_blank"); 
                  }
              };
              

              希望这会有所帮助。

              【讨论】:

              • 不错..您最终会访问该站点,但它仍然是一个传出链接?
              • 我创建此插件的目的是确保我的访问者在单击链接时不会离开我的网站,除非该链接目标位于我的网站内。这就是为什么我需要为传出链接制定特殊规则。
              • @GusDeCooL 我认为阻止人们离开您的网站去访问外部网站并不是一个好主意。如果你试图阻止他们,他们会找到其他方法并感到沮丧。还是我误会了你?
              • 他不想阻止人们离开他的网站。他只是希望外部链接为 _blank,以便他们在完成外部链接的站点后很容易找到返回他的站点的路。为此目的使用 _blank 是一种方法。
              • @JoakimBörjesson 感谢您向 Moin 解释 :)
              【解决方案14】:

              试试:

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

              【讨论】:

                【解决方案15】:
                <div id="myLinks"><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></div>
                <script type="text/javascript">
                jQuery(document).ready(function(){
                jQuery('#myLinks a').attr('target', '_blank');
                });
                </script>
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2023-04-03
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多