【问题标题】:using localStorage in html5在 html5 中使用 localStorage
【发布时间】:2012-02-25 22:16:28
【问题描述】:
<form>
<input name="Team1" id="team1" type="text" value="Team1?">
<button id="dostuff" value="Go">Go</button>
</form>

<div id ="nicteamcolumn">Team: </div>

<script>
$('#dostuff').click(function(e) {

var team1 = $('input[name="Team1"]').val();

if (typeof(Storage) !== "undefined") {
            if (localStorage.teamlist) {
                localStorage.teamlist= localStorage.teamlist + team1;

            }
            else {
            localStorage.teamlist = " ";    
            }

            $('#nicteamcolumn').html("Team:" + "<br>" + localStorage.teamlist + "<br>")
      }
}
</script>

基本上,当单击按钮时,我从 Team1 获取输入,将其添加到 localStorage.teamlist,并将 #nicteamcolumn 的 html 更改为 localStorage.teamlist

我第一次点击按钮时得到一个奇怪的输出。它一遍又一遍地打印团队 1 的值。第二次点击似乎工作正常,以及当我关闭页面并返回并继续添加到列表时。

任何帮助将不胜感激?

【问题讨论】:

  • 您的按钮会在您单击它时提交表单,因为默认情况下按钮是提交按钮。由于您的表单没有操作参数,因此提交它会导致页面重新加载。将您的按钮更改为具有属性 type="button",然后查看单击它时会发生什么。

标签: javascript html local-storage


【解决方案1】:

它会一遍又一遍地打印团队 1 的值。第二次点击似乎正在工作

这是因为localStorage 对象是持久的。即使脚本的源代码发生更改,localStorage 值仍然存在。您可能会将localStoragesessionStorage 混淆。

修复代码:

  • 通过在最后一个 } 之后放置 ); 来修复语法错误。
  • typeof 不是一个函数,请不要让它看起来像一个,去掉括号。
  • 第一次,nothing 将打印出来,因为您添加的是空格而不是 Team1 的值。
  • 建议不要直接设置属性,而是使用.getItem.setItem方法,避免使用冲突键名的错误。
  • 您当前的“列表”是一组串联的字符串。这不容易维护。要么使用唯一的分隔符来分隔你的值,要么使用JSON.stringifyJSON.parse 来存储真实的数组。

演示:http://jsfiddle.net/BXSGj/

代码(使用 JSON):

$('#dostuff').click(function(e) {
    e.preventDefault(); // Prevent the form from submitting
    var team1 = $('input[name="Team1"]').val();
    if (typeof Storage !== "undefined") {
        // Will always show an array:
        var teamlist = JSON.parse(localStorage.getItem('teamlist') || '[]');
        teamlist.push(team1);
        localStorage.setItem('teamlist', JSON.stringify(teamlist));
        $('#nicteamcolumn').html("Team:<br>" + teamlist.join('<br>') + "<br>");
    }
});

使用分隔符(只显示不同的行):

        var SEP = '|'; // Separator example
        var teamlist = (localStorage.getItem('teamlist') || '').split(SEP);
        teamlist.push(team1);   // Still the same
        localStorage.setItem('teamlist', teamlist.join(SEP));

要删除存储的项目,请使用localStorage.removeItem 方法:

localStorage.removeItem('teamlist');

另请参阅:Compability table 以获取 Storage 对象。

【讨论】:

    猜你喜欢
    • 2013-11-25
    • 2011-10-04
    • 2018-08-13
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多