如何在刷新页面时自动保存输入

问题描述 投票:0回答:1

我希望能够在刷新页面时保存我在网站上输入的输入

function num() {
  var number = prompt("Enter number");
  document.getElementById("number").innerHTML = number;

}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
<button onclick="num()">Click here to edit number</button>

<table>
  <tr>
    <th colspan=2>Something</th>
  </tr>
  <tr>
    <td>Name</td>
    <td id="number"><!-- this is where I want input to show --> </td>
  </tr>
</table>

我希望能够刷新页面,并输入我输入的数字,保持在那里。

javascript html variables html-table
1个回答
0
投票

尝试使用以下代码更新您的代码

//if value exist place it otherwise show 0
function onloadFunc() {
  document.getElementById("number").innerHTML = localStorage.getItem("number") || 0;
}

window.onload = onloadFunc;

function num() {
  var number = prompt("Enter number");
  // set the value in local storage
  localStorage.setItem("number", number);
  document.getElementById("number").innerHTML = number;
}
© www.soinside.com 2019 - 2024. All rights reserved.