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

Jquery 使用$(this.attr(';target';,';#u blank';)更改锚定会导致链接在新窗口和当前窗口中打开,jquery,Jquery,嘿,我最近编写了一些Jquery,使用以下代码使站点外部的所有链接都具有target=“\u blank”: $('div#outer-wrapper a').each(function(){ var hrefpull = $(this).attr("href"); if (typeof hrefpull != 'undefined'){ if (hrefpull.charAt(0) == '/' || hrefpull.charAt(0) == '#' || h

嘿,我最近编写了一些Jquery,使用以下代码使站点外部的所有链接都具有target=“\u 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=“\u blank”没问题。。。然而。。。当我单击链接时,它会在新窗口和当前窗口中加载链接。这是什么原因造成的,我如何修复?

我建议您在javascript的新窗口中打开链接,而不是添加target=“\u 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;
    }
  });
});

看起来您正试图在新窗口中打开指向外部网站的链接。这就是我通常的处理方式,包括可怕的冗长评论

// 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 ]);
        });
    }
});

您是否尝试将
$(this.attr('href','#')
添加到
$(this.attr('target','u blank')
行的正下方?这样做不会使链接无法移动…您是对的。我错过了!我不知道是什么引起了这个错误。你能在不同的浏览器中复制它吗?这是迄今为止最接近的答案,但我仍然不太明白是什么导致了这个问题!答案是window.open和return false,尽管上面的代码不完整。谢谢你的帮助!很抱歉。我现在已经修复了丢失的代码,以防有人来这里。