假设我有以下代码:
<div id="link_other">
<ul>
<li><a href="http://www.google.com/">google</a></li>
<li>
<div class="some_class">
dsalkfnm sladkfm
<a href="http://www.yahoo.com/">yahoo</a>
</div>
</li>
</ul>
</div>
在这种情况下,JavaScript会将target="_blank"
添加到link_other
中的所有链接。
我如何使用JavaScript做到这一点呢?
发布于 2009-04-29 21:28:23
/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
// not using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
// jquery is prettier. :-)
您还可以添加一个title标记来通知用户您正在执行此操作,以警告他们,因为如前所述,这不是用户所期望的:
$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
发布于 2009-04-29 21:08:38
非jquery:
// Very old browsers
// var linkList = document.getElementById('link_other').getElementsByTagName('a');
// New browsers (IE8+)
var linkList = document.querySelectorAll('#link_other a');
for(var i in linkList){
linkList[i].setAttribute('target', '_blank');
}
发布于 2009-04-29 21:04:21
使用jQuery:
$('#link_other a').each(function(){
$(this).attr('target', '_BLANK');
});
https://stackoverflow.com/questions/804256
复制相似问题