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。谢谢。
您在每次迭代中配置相同的对象
在每次迭代中创建新对象
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);
}