且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何添加target =" _blank"到指定div内的链接?

更新时间:2022-02-10 08:50:03

/* 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.');