我正在尝试弄清楚如何在刷新页面后将“标记为已读”保留为“标记为未读”。反之亦然。如何使用localStorage保存数据?到目前为止,这是我的“标记为已读”代码:
function readunread() {
currentvalue = document.getElementById("readunread").value;
if(currentvalue == "Mark as Unread"){
document.getElementById("readunread").value = "Mark as Read";
} else{
document.getElementById("readunread").value = "Mark as Unread";
}
}
body {
background:black;
}
.button {
border: none;
color: white;
font-family: Corbel;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
background-color: black;
}
input[type=button] {
font-size: 20px;
font-family: Corbel;
text-decoration: none;
color: white;
border: none;
background: none;
cursor: pointer;
margin: 0;
padding: 0;
}
<input type = "button" value = "Mark as Read" id = "readunread" onclick = "readunread();">
我点击“标记为已读”,它变成“标记为未读”。但刷新页面后,又回到“标记为已读”。我该如何避免这种情况?
最佳答案
在您的脚本中,您需要更改两件事:
<script>
function readunread() {
currentvalue = document.getElementById("readunread").value;
if (currentvalue == "Mark as Unread") {
document.getElementById("readunread").value = "Mark as Read";
// 1. Update the localstorage
localStorage.setItem("readunread", "Mark as Read");
} else {
document.getElementById("readunread").value = "Mark as Unread";
// 1. Update the localstorage
localStorage.setItem("readunread", "Mark as Unread");
}
}
</script>
<input
type="button"
value="Mark as Read"
id="readunread"
onclick="readunread();"
/>
<script>
// 2. Get the value from the local storage
function loadInitialValue() {
const localValue = localStorage.getItem("readunread");
console.log(localValue);
if (localValue == "Mark as Unread") {
document.getElementById("readunread").value = "Mark as Unread";
} else {
document.getElementById("readunread").value = "Mark as Read";
}
}
loadInitialValue(); // Make sure to call the function
</script>
关于javascript - 如何用localStorage制作 “Mark as Read”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74591005/