如何使用本地存储中的数据元素将 <li> 添加到 <ul>

因此,我尝试创建一个输入列表,其中包含从对象数组中获取的唯一值。但由于某种原因,它只迭代一次并停止。


function loadLayer() {

//Get the object from local storage

var project = JSON.parse(localStorage.getItem('project'));


var projectLayers = project.layers


for (var x = 0; x < projectLayers.length; x++) {

    var x = createLayer(projectLayers[x].name)

    appendLayer(x)

  }

}

所以项目层基本上是一个数组[{id=1,name="bob},{id=2,name="kevin"}]


function createLayer(name) {

  var li = document.createElement("li");

  li.className = "list-group-item"

  var x = document.createElement("INPUT")

  x.setAttribute("type", "text")

  x.setAttribute("value", name)

  li.appendChild(x)

  return li

}


function appendLayer(layer) {

  var layerList = document.getElementById("layerList")

  layerList.appendChild(layer)

}

而appendlayer只是将li添加到ul


然而,在我运行该程序后,我只有一个


里面有一个包含 bob 的输入。另一个没去哪里。我尝试打印以查看是否调用了第二个循环,但似乎没有。我不知道为什么,被困了几个小时。


12345678_0001
浏览 87回答 2
2回答

开满天机

就像您被告知的那样,您需要小心命名变量的方式。其次,我还建议使用let而不是var。因为您可以轻松地覆盖在其初始范围之外使用var声明的变量。现在到您的代码: 我对您的代码进行了一些编辑,尤其是loadLayer 函数,并将两个名称附加到列表中:<script>&nbsp; &nbsp; let projectList = [&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id:1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name:"bob"&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id:2,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name:"kevin"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ]&nbsp; &nbsp; function loadLayer() {&nbsp; &nbsp; &nbsp; &nbsp; window.localStorage.setItem('project', JSON.stringify(projectList));&nbsp; &nbsp; &nbsp; &nbsp; let p = JSON.parse(window.localStorage.getItem('project'));&nbsp; &nbsp; &nbsp; &nbsp; for (let i = 0; i < p.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let projectName = createLayer(p[i].name)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; appendLayer(projectName)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; function createLayer(name) {&nbsp; &nbsp; &nbsp; &nbsp; let li = document.createElement("li");&nbsp; &nbsp; &nbsp; &nbsp; li.className = "list-group-item"&nbsp; &nbsp; &nbsp; &nbsp; let x = document.createElement("INPUT")&nbsp; &nbsp; &nbsp; &nbsp; x.setAttribute("type", "text")&nbsp; &nbsp; &nbsp; &nbsp; x.setAttribute("value", name)&nbsp; &nbsp; &nbsp; &nbsp; li.appendChild(x)&nbsp; &nbsp; &nbsp; &nbsp; return li&nbsp; &nbsp; }&nbsp; &nbsp; function appendLayer(layer) {&nbsp; &nbsp; &nbsp; &nbsp; let layerList = document.getElementById("layerList")&nbsp; &nbsp; &nbsp; &nbsp; layerList.appendChild(layer)&nbsp; &nbsp; }&nbsp; &nbsp; loadLayer()</script>

不负相思意

您将循环中迭代的变量命名为 as ,x如果var x = createLayer(projectLayers[x].name)与它发生冲突,请更改其中之一。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5