如何在jQuery中放置target ="_ blank"?

elm*_*mas 21 jquery dom

我尝试了许多变种来target="_blank"与jQuery 建立链接,但我无法让它工作.

这是我的代码:

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"))

                );
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Che*_*try 77

太多的信息!这应该工作正常:

$("a").attr("target","_blank");
Run Code Online (Sandbox Code Playgroud)

请参阅此处的示例http://jsbin.com/evexi/edit.它完美地运作.

  • 如果您只想在新窗口中打开外部链接,那么此正则表达式可能会有所帮助.`$( "一个[HREF ^ = 'HTTP']")ATTR( '目标', '_空白');` (10认同)

CMS*_*CMS 16

由于您正在迭代作为锚的子元素的图像元素,因此在循环的开头可以设置它:

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


小智 10

为了增加这个答案非常简单,这个方法非常有用,你可以定位多种类型的链接,例如:

$("#whatever_id a, #another_id, #yet_another, #etc").attr("target","_blank");
Run Code Online (Sandbox Code Playgroud)

只需用逗号分隔不同的id.


小智 8

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

<a href='#' class='any existing classes target-blank'>Opens in a new window</a>
Run Code Online (Sandbox Code Playgroud)

然后添加一滴jQuery

$("a.target-blank").attr('target','_blank');
Run Code Online (Sandbox Code Playgroud)

有效的xhtml和一个理解target ='_ blank'的DOM!