假设我有以下代码:
<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"
到 div 内的所有链接link_other
.
我怎样才能使用 JavaScript 做到这一点?
/* 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. :-)
您还可以添加一个标题标签来通知用户您正在这样做,以警告他们,因为正如已经指出的那样,这不是用户所期望的:
$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)