[英]How to use javascript to add target=“_blank” to some links only?
是否可以使用javascript将target="_blank"
添加到URL中包含以下内容的所有链接: profile.php?id=
The following should work: 以下应该工作:
var aElems = document.links;
for (var i=0,len = aElems.length; i<len; i++){
if (aElems[i].href.indexOf('profile.php?id=') != -1){
aElems[i].target = '_blank';
}
}
Edited to improve the performance of the above code, removing document.links
and replacing it with document.getElementsByTagName('a')
: 编辑以提高上述代码的性能,删除
document.links
并将其替换为document.getElementsByTagName('a')
:
var aElems = document.getElementsByTagName('a');
for (var i=0,len = aElems.length; i<len; i++){
if (aElems[i].href.indexOf('profile.php?id=') != -1){
aElems[i].target = '_blank';
}
}
It's worth noting, though, that using Chris Fulstow 's querySelectorAll()
-enabled $('a[href*="profile.php?id="]')
approach is marginally faster (in Chromium 14/Ubuntu 11.04): JS Perf speed-test . 不过,值得注意的是,使用Chris Fulstow的启用
$('a[href*="profile.php?id="]')
querySelectorAll()
$('a[href*="profile.php?id="]')
方法的速度略快(在Chromium 14 / Ubuntu 11.04中): JS性能测试 。 Therefore, the following is the fastest (in browsers that support querySelectorAll()
): 因此,以下是最快的(在支持
querySelectorAll()
浏览器中):
var aElems = document.querySelectorAll('a[href*="profile.php?id="]');
for (var i=0,len = aElems.length; i<len; i++){
if (aElems[i].href.indexOf('profile.php?id=') != -1){
aElems[i].target = '_blank';
}
}
Above assertion 'fastest' supported by JS Perf comparison , at least in Chromium 14/Ubuntu 11.04. 至少在Chromium 14 / Ubuntu 11.04中,上述JS Perf比较支持“最快”的断言。 Bear in mind, of course, that IE < 8, and Firefox 3 , aren't going to play well with this approach.
当然,请记住IE <8和Firefox 3不能很好地使用这种方法。
Of course, the above should be corrected to: 当然,以上内容应更正为:
var aElems = document.querySelectorAll('a[href*="profile.php?id="]');
for (var i=0,len = aElems.length; i<len; i++){
aElems[i].target = '_blank';
}
This is because the if
condition was already evaluated by querySelectorAll()
, which makes the if
entirely redundant. 这是因为
if
条件已经由querySelectorAll()
求值,这使得if
完全多余。
Modified JS Perf comparison: http://jsperf.com/anchor-selector-test/3 . 修改后的JS Perf比较:http://jsperf.com/anchor-selector-test/3 。
另一个jQuery解决方案,只是为了好玩。
$("a[href*='profile.php?id=']").attr("target", "_blank");
Use JQuery or look at their source and port their logic into your own code base: 使用JQuery或查看其源代码并将其逻辑移植到您自己的代码库中:
$(function(){
$('a').each(function(){
var $this = $(this);
if ($this.attr('href').indexOf('profile.php?id=') !== -1) {
$this.attr('target','_blank');
}
});
});
Demo: http://jsfiddle.net/KJv7D/ 演示: http : //jsfiddle.net/KJv7D/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.