javascript - 从数组创建无序列表的 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>
为什么它不工作,我怎样才能让它工作?
解决方案
您应该分开创建孩子和附加孩子的逻辑。
你的错误来自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)
推荐阅读
- netsuite - 永久转换项目收据循环
- xcode - Swift 包管理器在 Xcode 中创建多个目标方案
- android - 从 kotlin 的 firestore 读取文档中的字段时出现问题
- image-segmentation - 如何减少 U-Net 参数?
- c# - IBKR API购买零碎股票
- c++ - forward_iterator 概念的冗余?
- java - 尽管每行达到 onBindViewHolder(),Android Recycler 仍返回零输出
- r - 修改 SIR 模型以包含随机性
- html - 如何使用 CSS 定位这些 HTML 元素?
- android - 从 UI 线程请求 dao 流是安全的