我如何添加目标=“_blank"?到指定 div 中的链接? [英] How do I add target="_blank" to a link within a specified div?
本文介绍了我如何添加目标=“_blank"?到指定 div 中的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下代码:
<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>
在这种情况下,JavaScript 会将 target="_blank"
添加到 div link_other
中的所有链接.
我如何使用 JavaScript 做到这一点?
解决方案
/* 这里有两种不同的方法来做到这一点 *///使用jquery:$(document).ready(function(){$('#link_other a').attr('target', '_blank');});//不使用 jquerywindow.onload = 函数(){var anchors = document.getElementById('link_other').getElementsByTagName('a');for (var i=0; i
你也可以添加一个标题标签来通知用户你正在这样做,警告他们,因为正如已经指出的那样,这不是用户所期望的:
$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
Let's say I have the following code:
<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>
In this case, the JavaScript would add target="_blank"
to all links within the div link_other
.
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.');
这篇关于我如何添加目标=“_blank"?到指定 div 中的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文