更改锚点的href和目标

时间:2013-03-12 14:42:45

标签: javascript html

我写了这个,所以它用类名改变了锚点的href,但我也希望它能改变目标,我该如何添加呢?

window.onload = function() {
    var change = document.getElementsByTagName('a');
    for (var i = 0; i < change.length; i++) {
        if (change[i].className.match('(^|\\s+)classnamegoeshere(\\s+|$)')) {
          change[i].href = "/urlgoeshere";
            break;
        }      
    }
}

2 个答案:

答案 0 :(得分:5)

change[i].setAttribute('target', '_blank');

答案 1 :(得分:0)

试试这个

window.onload = function() {
  var change = document.getElementsByTagName('a');
  for (var i = 0, j =change.length; i < j ; i++) {
     if ((' ' + change[i].className + ' ').indexOf(' ' + "smeCls" + ' ') > -1) {
         change[i].href = "http://www.google.com";
     }      
  }
}