javascript - 如何用localStorage制作 “Mark as Read”?

标签 javascript html css local-storage

我正在尝试弄清楚如何在刷新页面后将“标记为已读”保留为“标记为未读”。反之亦然。如何使用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/

相关文章:

javascript - 我如何将 Angular JS 构建的表单提交到电子邮件地址

javascript - 无法将类添加到元素

javascript - 隐藏手机面包屑导航中的最后一个文本 block - Prestashop

css - WebStorm 中的 PostCSS 语法

javascript - 检测用户何时使用 CSS 调整 Div 大小 : both

javascript - 有没有办法将初始化函数传递给 Orbit 幻灯片?

javascript - 在 Magnific Popup 顶部显示 JQuery Modal

javascript - 在同一页面上显示内容

javascript - 如何将下拉列表的选择值保存到MySQl表

html - 转换背景和固定位置时如何摆脱重叠?