我正在使用示例脚本填充我网站中的表格。基本上我想复制保存一个人的答案,所以如果他们刷新页面,他们的选择仍然存在。我有功能添加项目到表,清除所有按钮工作,主要问题是删除按钮将无法正常工作。我得到了错误;在控制台中“找不到变量”,即使我可以通过检查console.log(window.localStorage);
window.addEventListener("load",updateTable,false);
function updateTable() {
var tbody = document.getElementById("output");
while (tbody.getElementsByTagName("tr").length > 0) {
tbody.deleteRow(0);
}
var row;
if (localStorage.length==0) {
row = tbody.insertRow(i);
cell = row.insertCell(0);
cell.colSpan="4";
cell.innerHTML = "Nothing to Show";
}
for (var i=0; i < localStorage.length; ++i) {
row = tbody.insertRow(i);
cell = row.insertCell(0);
cell.innerHTML = i;
cell = row.insertCell(1);
cell.innerHTML = localStorage.key(i)
cell = row.insertCell(2);
cell.innerHTML = localStorage.getItem(localStorage.key(i));
cell = row.insertCell(3);
cell.innerHTML = '<button class="btn btn-danger btn-sm" onclick="deleteItem('+localStorage.key(i)+');"><i class="fa fa-trash-o"></i> Delete</button>';
}
}
function deleteItem(key) {
if (!confirm("Are you sure you want to delete this item?")) return;
localStorage.removeItem(key);
updateTable();
}
function clearStorage() {
if (!confirm("Are you sure you want to delete all local storage for this domain?")) return;
localStorage.clear();
updateTable();
}
function save() {
var key = document.getElementById("key").value;
var value = document.getElementById("value").value;
localStorage.setItem(key,value);
updateTable();
}
答案 0 :(得分:3)
您没有在删除调用中分隔键...
cell.innerHTML = '<button class="btn btn-danger btn-sm" onclick="deleteItem(\''+localStorage.key(i)+'\');"><i class="fa fa-trash-o"></i> Delete</button>';
注意我在密钥周围添加了引号。试试看,看看是否有帮助:)