炎炎設計
2022-10-21 17:28:46
我嘗試創建一個從數組創建無序列表的 DOM 函數。例如,如果您將數組 ["hello", "food", "sun"] 傳遞給它,它將創建無序列表:<ul><li>hello</li><li>food</li><li>sun</li></ul>然而,它什么也沒創造。這是我的 DOM 函數的代碼:<script>function create_list(array,id){var ul= document.createElement("ul")ul.setAttribute("id",id)//sets the id of the ul tag to the id specified as argument.for (var i=0 ; i<array.length ; i++){ul.appendChild.document.createElement("li").textContent= array[i]//creates list elements inside of the ul tag.}document.body.appendChild(ul)//adds the ul tag to the body of the html document.}//call the functioncreate_list(["hello","13","Kitchen"],13)</script>為什么它不工作,我怎樣才能讓它工作?
1 回答

函數式編程
TA貢獻1807條經驗 獲得超9個贊
您應該分開創建孩子和附加孩子的邏輯。
你的錯誤來自ul.appendChild.document.createElement..
我認為最好像下面這樣使用=)
function create_list(array, id) {
var ul = document.createElement("ul")
ul.setAttribute("id", id)
//sets the id of the ul tag to the id specified as argument.
for (var i = 0; i < array.length; i++) {
var li = document.createElement("li");
li.textContent = array[i]
ul.appendChild(li);
//creates list elements inside of the ul tag.
}
document.body.appendChild(ul)
//adds the ul tag to the body of the html document.
}
//call the function
create_list(["hello", "13", "Kitchen"], 13)
添加回答
舉報
0/150
提交
取消