javascript - 如何获取表单提交按钮以保存到 localStorage

标签 javascript html css

我是初学者,正在尝试弄清楚如何让它发挥作用。我有一个表单,我希望提交按钮能够保存到 localStorage。到目前为止,这就是我所拥有的。

<script>
function storeRecipe() {
    localStorage.setItem($("#recipe-name").val(), $("#recipe-
      description").val());
  console.log(Object.keys(localStorage));
}
</script>

<b>Recipe Name:</b>
<br>
<textarea id="recipe-name" rows="1" cols="35"></textarea>
<br><br>
<b>Recipe Description:</b>
<br>
<textarea id="recipe-description" rows="15" cols="35"></textarea>
<br><br>
<input type="submit" value="Send Recipe" onClick="storeRecipe()">

最佳答案

提交后,您可以停止提交表单并将每个输入字段保存为本地存储键。工作 jsfiddle:https://jsfiddle.net/mr4ms4zp/ .在 Mac 上打开控制台 cmd+opt+i 可以看到更改后的 localStorage 对象。

<form method="POST">
  <b>Recipe Name:</b>
  <br>
  <textarea id="recipe-name" rows="1" cols="35"></textarea>
  <br><br>
  <b>Recipe Description:</b>
  <br>
  <textarea id="recipe-description" rows="15" cols="35"></textarea>
  <br><br>
  <input type="submit" value="Send Recipe">
</form>

<script>
  document.querySelector('form').onsubmit = function(e) {
    e.preventDefault();
    var name = document.querySelector('#recipe-name').value;
    var description = document.querySelector('#recipe-description').value;
    localStorage["name"] = name;
    localStorage["description"] = description;
    console.log(localStorage);
  }
</script>

关于javascript - 如何获取表单提交按钮以保存到 localStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741727/

相关文章:

css - SIFR 3 : IE6 Extra Spacing

javascript - 如何使用 AngularJS 通过单选按钮过滤 json 数据?

html - 将标题文本与同一行的后续文本对齐

html - Foundation 5 div 样式

javascript - 我希望一段段落在检查和虎钳中检查复选框时通过风格获取线路

html - svg 虚线仅当鼠标悬停在路径上时才悬停

javascript - Chart.js 与数据库中的数据

javascript - 如何根据条件延迟循环?

javascript - 带有 React Hooks 的 HoC

CSS 在 Firefox 中工作正常但在 IE 上无法正常显示?