我曾尝试创建一个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>
为什么它不起作用,我怎样才能使它起作用?
您应该将创建子级和追加子级的逻辑分开。
您的错误来自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)