2009-12-19 74 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!

相關問題