如何添加target =" _blank"到指定div内的链接? [英] How do I add target="_blank" to a link within a specified div?
本文介绍了如何添加target =" _blank"到指定div内的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下代码:
<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
。
In this case, the JavaScript would add target="_blank"
to all links within the div link_other
.
如何使用JavaScript执行此操作?
How can I do that using 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. :-)
您还可以添加标题标签以通知用户您正在执行此操作,警告他们,因为正如已经指出的那样,它不是用户期望的:
You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect:
$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
这篇关于如何添加target =" _blank"到指定div内的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文