我想知道如何在刷新页面后保持"标记为已读"和"标记为未读"的状态.反之亦然.如何使用本地存储保存数据?到目前为止,这是我对"Mark as Read"的代码:

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相关问答推荐

JS生成具有给定数字和幻灯片计数的数组子集

如何才能拥有在jQuery终端中执行命令的链接?

如何使覆盖div与可水平滚动的父div相关?

阿波罗返回的数据错误,但在网络判断器中是正确的

获取Uint8ClampedArray中像素数组的宽度/高度

如何在ASP.NET项目中使用Google Chart API JavaScript将二次轴线值格式化为百分比

使用getBorbingClientRect()更改绝对元素位置

在数组中查找重叠对象并仅返回那些重叠对象

如何在Bootstrap中减少网格系统中单个div的宽度

当我try 将值更改为True时,按钮不会锁定

使用线性插值法旋转直线以查看鼠标会导致 skip

如何找到带有特定文本和测试ID的div?

如何使用puppeteer操作所有选项

bootstrap S JS赢得了REACT中的函数/加载

P5play SecurityError:无法从';窗口';读取命名属性';Add';:阻止具有源的帧访问跨源帧

不允许在对象文本中注释掉的属性

与find()方法一起使用时,Mongoose中的$or运算符没有提供所有必需的数据

如何在preLoad()中自定义p5.js默认加载动画?

使用JavaScript或PHP从div ID值创建锚标记和链接

TS node 找不到依赖的模块