如何将输入数字存储在localStorage中,然后在以后加载它?

我正在尝试创建一个使用输入数字的程序,单击按钮时将其存储到localStorage中,然后在单击单独的按钮时将其加载。本质上是保存/加载功能。问题是我需要保存另一个函数的ID。


我已经尝试在保存/加载函数中调用其他函数,并且尝试了其他各种方法,但是对于使用localStorage(或任何类型的存储)而言,我是一个新手。


这是具有我要保存的ID(qty1)的函数,其后是我的保存/加载函数(似乎不起作用)。


function modify_qty(val) {

    var qty = document.getElementById('qty1').value;

    var new_qty = parseInt(qty,10) + val;

    var max = document.getElementById('max1').value;


    if (new_qty < 0) {

        new_qty = 0;

    }

    if (isNaN(new_qty)) {

        new_qty = 0;

    }

    if (new_qty > max) {

        new_qty = max;

    }


    document.getElementById('qty1').value = new_qty;

    return new_qty;

}

function save() {

    return function(modify_qty) {

    localStorage.setItem('qty', qty1);

    }

}

function load() {

    return function(modify_qty) {

    var qty1 = localStorage.getItem('qty');


    document.getElementById('qty1').value = qty1;

    return qty1;

    }

}

我需要保存函数将id“ qty1”保存到localstorage中,以便加载函数以后可以将其拉回并用保存的值替换当前值。现在,我认为保存/加载功能都不起作用,因为我保存值,重新加载,尝试加载,但没有任何反应。出于测试目的,我禁用了max变量,事实并非如此。


慕莱坞森
浏览 252回答 3
3回答

繁华开满天机

localStorage.setItem("qty", 5);const qty = localStorage.getItem("qty");const num = Number(qty); // or const num = parseInt(qty):console.log(num);

qq_笑_17

将行替换为localStorage.setItem('qty', qty1);:localStorage.setItem('qty', JSON.stringify(qty1));并与以下行localStorage.getItem('qty');:JSON.parse(localStorage.getItem('qty'));这应该可以解决问题。原因:&nbsp;localStorage将所有内容存储为string类型。因此,任何整数或数字也将转换为string。通过使用JSON函数,我们保留了type存储在中的原始值localStorage。

小唯快跑啊

我没有看到从代码中的函数返回函数的目的,也没有看到它与问题文本之间的关系。我看不到您对localStorage进行get和set硬编码使用的目的。除非变量名将是变量,否则会使读取变得复杂。localStorage.setItem('qty',123); === localStorage.qty=123;我相信要问的一个简化版本是...<input type="number" id="value"><input type="button" id="set" value="set"><input type="button" id="restore" value="restore"><script>&nbsp; &nbsp; document.getElementById('set').addEventListener("click", function() {&nbsp; &nbsp; &nbsp; &nbsp; localStorage.qty = document.getElementById('value').value;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; document.getElementById('restore').addEventListener("click", function() {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('value').value= localStorage.qty;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; document.getElementById('value').addEventListener("change", function() {&nbsp; &nbsp; &nbsp; &nbsp; let max = 10;&nbsp; &nbsp; &nbsp; &nbsp; if (this.value < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new_qty = 0;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (this.value > max) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.value = max;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });</script>但是,您可能能够在HTML标记上完成数据验证,而无需脚本进行验证。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript