假设我有以下代码:

<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 =&quot; _blank&quot; 添加到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.');

其他提示

非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');
}

请记住,Web开发人员和可用性专家通常认为这样做是不好的做法。雅各布·尼尔森(Jakob Nielson)对此表示要取消对用户浏览体验的控制:

  

尽可能避免产生多个浏览器窗口&#8212;采取“后退”远离用户的按钮可以让他们的体验如此痛苦,以至于它通常远远超过你想要提供的任何好处。产生第二个窗口的一个常见理论是它可以防止用户离开你的网站,但具有讽刺意味的是,它可能会产生相反的效果,阻止它们在需要时返回。

我认为这是W3C从XHTML 1.1规范中删除目标属性的基本原理。

如果您已采取这种方法,Pim Jager的解决方案很好。

更好用,更友好的想法是将图形附加到所有外部链接,向用户指示跟随链接将从外部链接。

您可以使用jquery执行此操作:

$('a[href^="http://"]').each(function() {
    $('<img width="10px" height="10px" src="/images/skin/external.png" alt="External Link" />').appendTo(this)

});

使用jQuery:

 $('#link_other a').each(function(){
  $(this).attr('target', '_BLANK');
 });

我将其用于每个外部链接:

window.onload = function(){
  var anchors = document.getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    if (anchors[i].hostname != window.location.hostname) {
        anchors[i].setAttribute('target', '_blank');
    }
  }
}

内联:

$('#link_other').find('a').attr('target','_blank');

将此用于每个外部链接

$('a[href^="http://"], a[href^="https://"]').attr('target', '_blank');
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top