1 回答
TA贡献1887条经验 获得超5个赞
可能不是很好的解决方案,但现在您可以在本地存储中添加键值。
希望,它会帮助你一些扩展。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<style>
section {
margin-top: 15px;
}
</style>
<script>
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);
console.log("Remove Item",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').replaceWith(tbl);
} else {
storageDiv.appendChild(tbl);
};
};
}
</script>
</head>
<body>
<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>
</body>
</html>
现在您可以将键和值添加到本地存储。
输出屏幕截图:
添加回答
举报