如何在jQuery中使用target="_blank"?

24

我尝试使用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"))

                );
            }
        }
    });

我该如何做到呢?

4个回答

84

信息过于详细了!这应该可以正常工作:

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

点击这里查看示例http://jsbin.com/evexi/edit。它可以完美地运行。


11
如果你只想在新窗口中打开外部链接,那么这个正则表达式可能会有所帮助。$("a[href^='http']").attr('target','_blank'); - Dylan Valade
我之前写过这个,但最近在为一个新网站工作时又用到了它:http://dpatrickcaldwell.blogspot.com/2010/03/custom-jquery-selector-for-external-and.html - D. Patrick

16

由于您正在迭代作为锚点子元素的图像元素,因此在循环开始时,您可以将其设置:

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

11

在这个超级有用的简单回答中,还有一个很棒的技巧,你可以同时针对多种类型的链接进行操作,例如:

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

只需用逗号将不同的 id 分开即可。


10

您可以给所有想要在新窗口中打开的链接添加一个class类,例如“target-blank”;

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

然后添加一滴jQuery
$("a.target-blank").attr('target','_blank');

有效的xhtml和理解target='_blank'的DOM!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接