我已经开始快速练习在 JS 中使用本地存储/会话存储,我的 LoadFromStorage 函数似乎有问题。每次调用控制台日志时,“replaceNode”都不是函数。
window.onload = function() {
document.getElementById('btnAdd').onclick = function() {
localStorage.setItem(document.getElementById("toStorageKey").value,
document.getElementById("toStorageValue").value);
LoadFromStorage();
}
document.getElementById('btnRemove').onclick = function() {
localStorage.removeItem(document.getElementById('toStorageKey').value);
LoadFromStorage();
}
document.getElementById('btnClear').onclick = function() {
localStorage.clear();
LoadFromStorage();
}
function LoadFromStorage() {
var storageDiv = document.getElementById('storage');
var tbl = document.createElement('table');
tbl.id = "storageTable";
if (localStorage.length > 0) {
for (var i = 0; i < localStorage.length; i++) {
var row = document.createElement("tr");
var key = document.createElement("td");
var val = document.createElement('td');
key.innerText = localStorage.key(i);
val.innerText = localStorage.getItem(key.innerText);
row.appendChild(key);
row.appendChild(val);
tbl.appendChild(row);
}
} else {
var row = document.createElement('tr');
var col = document.createElement('td');
col.innerText = 'No data in local storage.';
row.appendChild(col);
tbl.appendChild(row);
}
if (document.getElementById('storageTable')) {
document.getElementById('storageTable').replaceNode(tbl);
} else {
storageDiv.appendChild(tbl);
};
};
}
section {
margin-top: 15px;
}
<section>
Key: <input type="text" id="toStorageKey"><br> Value: <input type="text" id="toStorageValue"><br>
</section>
<section>
<button type="button" id="btnAdd">Add to storage</button>
<button type="button" id="btnRemove">Remove from storage</button>
<button type="button" id="btnClear">Clear storage</button>
</section>
<div id="storage">
<p>Current Storage Contents</p>
</div>
慕工程0101907
相关分类