为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

炎炎设计 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)


查看完整回答
反对 回复 2022-10-21
  • 1 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号