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。謝謝。
uj5u.com熱心網友回復:
問題
您在每次迭代中配置相同的物件
解決方案
在每次迭代中創建新物件
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/505811.html
標籤:javascript for循环 超链接
下一篇:是否可以在Lua中自動定義函式
