2009-12-19 76 views
19

我尝试了很多变化,把target="_blank"与jQuery链接,但我无法让它工作。如何在jQuery中放置target =“_ blank”?

这里是我的代码:

var thumbfile = "<?php echo $smit_iturl_v; ?>"; 
jQuery(document).ready(function() { 
    var actualHost = jQuery.trim(jQuery.url.attr("host")); 
    jQuery("a img").each(function (i) { 

     if (jQuery.trim(jQuery.url.setUrl(jQuery(this).attr("src")).attr("host")) == actualHost &&  
      (jQuery.url.setUrl(jQuery(this).attr("src")).attr("path")).indexOf("wp-content") != -1 && 

      isImage(jQuery.url.setUrl(jQuery(this).attr("src")).attr("file"))) { 

      var parentTag = jQuery(this).parent().get(0).tagName; 
      parentTag = parentTag.toLowerCase(); 

      if (parentTag == "a" && 
      jQuery.url.setUrl(jQuery(this).parent().attr("href")).attr("host") == actualHost && 
      jQuery.url.setUrl(jQuery(this).parent().attr("href")).attr("path").indexOf("wp-content") != -1 && 
      isImage(jQuery(this).parent().attr("href"))) { 

       var description = (jQuery(this).attr("alt") == "") ? jQuery(this).attr("title") : jQuery(this).attr("alt"); 
       jQuery(this).parent().attr("href", thumbfile + 
         "?title=" + jQuery(this).attr("title") + 
         "&description=" + description + 
         "&url=" + stripDomain(jQuery(this).parent().attr("href")) 

       ); 
      } 
     } 
    }); 

我该怎么办呢?

回答

16

既然你迭代是一个锚的孩子的形象元素,在循环的开始,你可以将其设置:

//... 
jQuery("a img").each(function (i) { 
    // 'this' is the img element, you should get the parent anchor 
    jQuery(this).parent().attr('target', '_blank'); 
    //... 
}); 
72

太多的信息!这应该工作得很好:

$("a").attr("target","_blank"); 

看到这里的例子http://jsbin.com/evexi/edit。它完美的作品。

+9

如果你只想在新窗口中打开外部链接,那么这个正则表达式可能会有帮助。 '$(“a [href^='http']”)。attr('target','_ blank');' – 2013-01-09 17:00:33

+0

谢谢你的队友,帮帮我 – DextrousDave 2013-04-02 09:16:50

+0

疯狂有用,谢谢! – 2013-11-28 04:30:17

10

要添加到这个答案,这是超级有用的方式的真棒简单,可以针对多种类型的链接,例如:

$("#whatever_id a, #another_id, #yet_another, #etc").attr("target","_blank"); 

只要保持不同的ID以逗号分隔。

7

你可以给你想在新窗口中打开一个类的所有链接,例如'target-blank';

<a href='#' class='any existing classes target-blank'>Opens in a new window</a> 

再加入jQuery的

$("a.target-blank").attr('target','_blank'); 
一滴

有效XHTML和了解目标= '_空白' 一个DOM!

相关问题