使用$(this).attr('target','_ blank')更改锚点会导致链接在新窗口和当前窗口中打开

时间:2011-03-23 20:27:19

标签: jquery

嘿那里,我最近写了一些Jquery,使用以下代码使网站外部的所有链接都具有target =“_ blank”:

$('div#outer-wrapper a').each(function(){
    var hrefpull = $(this).attr("href");
    if (typeof hrefpull != 'undefined'){
        if (hrefpull.charAt(0) == '/' || hrefpull.charAt(0) == '#' || hrefpull.charAt(0) == ''){
            // Skips over anything with a / # or nothing!
            }else{
            var checker = hrefpull.split("/");
            if (checker[2] != $baseUrl){
                $(this).attr('target', '_blank')
            }
        }
    }
});

现在它添加了target =“_ blank”没问题......但是......当我点击链接时,它会在新窗口和当前窗口中加载链接。造成这种情况的原因是什么,以及如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

我建议你在javascript的新窗口中打开链接,而不是添加target =“_ blank”。像这样:

$(function(){
  $('div#outer-wrapper a').click(function(){
    var href = $(this).attr("href");
    if (!(href || href.charAt(0) == '/' || href.charAt(0) == '#' || href.charAt(0) == '')){
      window.open(this.href);
      return false;
    }
  });
});

答案 1 :(得分:1)

看起来您正试图在新窗口中打开指向外部网站的链接。这就是我通常处理这个问题的方法,并附有可怕的详细评论。

// Select the links that start with "http" in their href
$("a[href^=http]").each(function(){
    // Do nothing to the internal links
    if (this.href.indexOf(location.hostname) == -1){
        $(this)
            // Add a class to style external links
            .addClass("external")
            // Get our semantic on
            .attr({ "rel":"external" })
            // Do stuff on click like...
            .click(function(e){
                // Prevent opening the link in this window
                e.preventDefault();
                // Open the link in a new window
                window.open(this.href);
                // Use Google Analytics to track this click
                _gaq.push([ '_trackEvent', 'Referrals', 'click', this.href ]);
        });
    }
});