如何使用for循环创建多个超链接html? (适用于 Chrome 扩展程序)

问题描述 投票:0回答:1
function createDropDown(){
  const tree = document.createDocumentFragment();
  const link = document.createElement('a');
  for(let index = 0; index < urlList.length; index++){
    link.appendChild(document.createTextNode(urlList[index]));
    link.setAttribute("href", urlList[index])
    link.setAttribute("id", "link "+index)
    tree.appendChild(link);
    document.getElementById("hyperlinks").appendChild(tree);

这是我的代码,我对 JS 和 HTML 相当陌生。我的目标是拥有一个带有超链接 id 的硬编码 div。在此 div 中,我想为“urlList”变量(URL 数组)的长度放置多个超链接。

我得到的结果是插入一个包含所有 URL 文本的超链接。与超链接关联的链接也恰好是 urlList 变量中的最后一个 URL。谢谢。

javascript for-loop hyperlink
1个回答
0
投票

问题

您在每次迭代中配置相同的对象

解决方案

在每次迭代中创建新对象

for(let index = 0; index < urlList.length; index++) {
  const tree = document.createDocumentFragment();
  const link = document.createElement('a');
  link.appendChild(document.createTextNode(urlList[index]));
  link.setAttribute("href", urlList[index])
  link.setAttribute("id", "link "+index)
  tree.appendChild(link);
  document.getElementById("hyperlinks").appendChild(tree);
}
© www.soinside.com 2019 - 2024. All rights reserved.