【问题标题】:Save value in reload page javascript在重新加载页面 javascript 中保存值
【发布时间】:2017-05-02 00:26:33
【问题描述】:

我想在页面重新加载时将数据保存在输入中,但我不想 知道为什么我的代码不起作用。这是我的 html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
        <label>nom:</label> <input type="text" value=""/></br>
        <label>prenom:</label><input type="text" value=""/>
        <script type="text/javascript">
        window.onbeforeunload = function(){
        localStorage.setItem(nom, document.getElementsByTagName('input')[0].value);
        localStorage.setItem(prenom, document.getElementsByTagName('input')[1].value);
            }
    document.addEventListener("DOMContentLoaded",function(){
            var nom = localStorage.getItem(nom);
            var prnom = localStorage.getItem(prenom);
            if(nom!==null&&prenom!==null) {                 
            document.getElementsByTagName('input')[0].value = nom;
            document.getElementsByTagName('input')[1].value = prenom;
            }
        });

         </script>
</body>
</html>

【问题讨论】:

  • 您的代码在页面加载时设置了 localStorage 值,这意味着它将其设置为无文本,因此代码不会保存。使用来自 sn-p 的代码。

标签: javascript html window local-storage onbeforeunload


【解决方案1】:

确保在变量名中使用引号:

localStorage.setItem('nom', document.getElementsByTagName('input')[0].value);

或者你可以使用这个更简单的:

localStorage.nom = document.getElementsByTagName('input')[0].value;

您的代码在页面加载时设置了 localStorage 值,这意味着它将其设置为无文本,因此代码不会保存。

使用下面的代码:

window.onbeforeunload = function() {
  var nom = localStorage.nom;
  var prnom = localStorage.prenom;
  if (nom !== null && prenom !== null) {
    document.getElementsByTagName('input')[0].value = nom;
    document.getElementsByTagName('input')[1].value = prenom;
  }
};
<label>nom:</label> <input type="text" onchange="localStorage.nom = document.getElementsByTagName('input')[0].value" /></br>
<label>prenom:</label><input type="text" onchange=" localStorage.prenom = document.getElementsByTagName('input')[1].value" />

重要提示:使用计算机上的代码,因为 localStorage 在堆栈溢出 sn-ps 上不起作用

【讨论】:

  • 我现在试试这个解决方案并不能解决问题:/
  • 您的代码在页面加载时设置了 localStorage 值,这意味着它将其设置为无文本,因此代码不会保存。使用来自 sn-p 的代码。
  • thanx 我现在尝试,这解决了我的问题,我在输入中设置了一个默认值并重新加载,这很好用 localStorage.nom = document.getElementsByTagName('input')[0].value;
  • localStorage.nom = localStorage.nom || ""放入onbeforeunload函数中,如果是undefined,则设置一个默认值。
  • 好吧,我去问你有没有使用 angularjs 的解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 2013-04-21
  • 2013-10-04
相关资源
最近更新 更多