猿问

从数组创建无序列表的 DOM 函数

我尝试创建一个从数组创建无序列表的 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 function

create_list(["hello","13","Kitchen"],13)


</script>

为什么它不工作,我怎样才能让它工作?


炎炎设计
浏览 90回答 1
1回答

函数式编程

您应该分开创建孩子和附加孩子的逻辑。你的错误来自ul.appendChild.document.createElement..我认为最好像下面这样使用=)function create_list(array, id) {&nbsp; var ul = document.createElement("ul")&nbsp; ul.setAttribute("id", id)&nbsp; //sets the id of the ul tag to the id specified as argument.&nbsp; for (var i = 0; i < array.length; i++) {&nbsp; &nbsp; var li = document.createElement("li");&nbsp; &nbsp; li.textContent = array[i]&nbsp; &nbsp; ul.appendChild(li);&nbsp; &nbsp; //creates list elements inside of the ul tag.&nbsp; }&nbsp; document.body.appendChild(ul)&nbsp; //adds the ul tag to the body of the html document.}//call the functioncreate_list(["hello", "13", "Kitchen"], 13)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答