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

我尝试了很多变种来将target="_blank"放在与jQuery的链接中,但我无法让它工作。

这是我的代码:

 var thumbfile = ""; 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")) ); } } }); 

我该怎么做?

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

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

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

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

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

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

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

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

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

 Opens in a new window 

然后添加一滴jQuery

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

有效的xhtml和理解target =’_ blank’的DOM!