我在本地存储中有几个元素,希望在屏幕上显示它们。我通过遍历列表并使用JavaScript创建元素然后追加它们来实现这一点。这样做运行良好,除了我添加的按钮只会被添加到最后一个元素。我无法弄清楚原因。我可以将其他文本追加到相同的li元素,但不能追加按钮。
任何帮助都将不胜感激,谢谢!
上面的结果是:来自存储的密钥(1)
来自存储的密钥(2)
来自存储的密钥(3) 点击我
任何帮助都将不胜感激,谢谢!
document.getElementById('savedScenarios').appendChild(listSavedScenarios());
function listSavedScenarios() {
// Create the list element:
var listElement = document.createElement('ul');
var button = document.createElement("BUTTON");
button.setAttribute("id", "load");
var t = document.createTextNode("CLICK ME");
button.appendChild(t);
for(var i = 0; i < localStorage.length; i++) {
// Create the list item:
var listItem = document.createElement('li');
//Get the local storage name and add it to the list elmt
listItem.appendChild(document.createTextNode(localStorage.key(i)));
listItem.appendChild(button);
//update list
listElement.appendChild(listItem);
}
return listElement;
}
上面的结果是: