简体   繁体   English

如何用链接数组替换锚标记的href?

[英]How to replace href of anchor tags with array of links?

// I am trying to replace href with array of links // 我正在尝试用链接数组替换 href

    var link = ['replaceLink1', 'replaceLink2'];
    var links = document.querySelectorAll('a');
    for(var i = 0; i < link.length; i++){
      for(var j = 0; j < links.length; j++){
        links[j].setAttribute('href',link[i]);
       }
    }

you don't need to loops just remove one and use the iterator to go throw both arrays你不需要循环只需删除一个并使用迭代器去抛出两个数组

 var link = ['replaceLink1', 'replaceLink2']; var links = document.querySelectorAll('a'); for (var i = 0; i < link.length; i++) { links[i].setAttribute('href', link[i]); }
 <a href="/link1" > click me ! </a> <a href="/link2" >click me ! </a>

you can loop with for of loop each anchor tag in the page and replace the href attribute with the corresponding link from an array (that have to be the same size as all the links on the page otherwise you'll get undefined as a link) like so:您可以使用for of循环页面中的每个锚标记,并用数组中的相应链接替换href属性(必须与页面上的所有链接大小相同,否则您将无法定义为链接)像这样:

 var linksToReplace = ['replaceLink1', 'replaceLink2']; var links = document.querySelectorAll('a'); for (let [i, link] of links.entries()) { link.setAttribute('href', linksToReplace[i]); }
 <a href="/link1"> click me ! </a> <a href="/link2">click me ! </a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM