【问题标题】:Appending data to localstorage issue将数据附加到本地存储问题
【发布时间】:2018-09-25 12:58:39
【问题描述】:

如果答案正确,我会在本地存储中设置一个字符串对象data.color。然后每次答案正确时,我都想在本地存储中记录并打印结果。

也许我的逻辑有问题,重新加载页面时文本没有正确附加,只有最后一个结果输出到 div。当答案正确时,我想将每个结果附加到本地存储中。

$('#butn').click(function(e) {
     $.ajax({
            type: "POST",
            url: "validation.php",
            dataType: "json",
            data: $("input").serialize(),
        }).done(function(data) {
         if (data.answer) { //if answer is correct
         localStorage.setItem("ColorStorage", data.color); //set in local storage the string object
          $("#result").append(localStorage.getItem("ColorStorage"));//print result to html
            }
        });
        });
        if (localStorage.getItem("ColorStorage"))  {/*if local storage is set..*/
    $("#result").append(localStorage.getItem("ColorStorage"));
    }

html:

  <div id="result"></div>

【问题讨论】:

    标签: javascript jquery ajax local-storage


    【解决方案1】:

    在设置之前获取项目。

    let answers = data.color + "," + localStorage.getItem("ColorStorage");
    localStorage.setItem("ColorStorage", answers);
    

    【讨论】:

    • 在设置之前使用answers = answers === null ? 0 :answers ;之类的东西来防止null输出到本地存储的末尾
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2014-07-07
    • 2014-09-02
    相关资源
    最近更新 更多