我想使用 localStorage 存储用户输入值,然后在倒计时器中使用该值。
这是用户输入数据的 HTML:
<form action='/' method= 'GET' id='settings'>
<label> Work Time </label>
<input class='settingInput' type='number' id='workInput'>
<label id='short-break'> Short Break </label>
<input class='settingInput' id='shortBreak'>
<label id='long-break'> Long Break </label>
<input class='settingInput' id='longBreak'>
<button id = 'set-values'>Submit</button>
</form>
这是用于存储和检索数据的 JavaScript:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
这是整个项目的代码笔:https://codepen.io/Games247/pen/XWJqebG
这是我第一次使用 setItem 和 getItem,所以我可能会忽略一些明显的东西。
目前看起来一对括号存储在 localStorage 中,workTimeKey 应该在该位置。
最佳答案
您在 codepen 上的链接代码有问题,事实上,此处发布的代码纠正了所述问题。
var workTimeSerialized = JSON.stringify(document.getElementById('workInput'));
上面是您的代码笔,问题是您正在尝试将 HTML 元素序列化为 JSON,而不是它的值,因此您会在 session 存储中看到“{}”。
您需要确保它是输入元素的值,而不是您序列化的元素本身。就像我提到的,您在此处发布的代码解决了该问题;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
注意:每当您在 session 存储中看到“[]”或“{}”而不是您想要的值时,您要么直接传递一个对象,要么传递一个元素。
编辑: “你很可能两者都不是”
您的输入值应该在提交点击处理程序中读取,否则,您将在提交之前而不是之后获得输入的值
所以你的代码:
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
submitButton.addEventListener('click', (e) => {
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
变成:
submitButton.addEventListener('click', (e) => {
var workInputValue = document.getElementById('workInput').value;
var workTimeSerialized = JSON.stringify(document.getElementById('workInput').value);
var workTimeFinal = JSON.parse(localStorage.getItem('workTimeKey'));
localStorage.setItem('workTimeKey', workTimeSerialized);
console.log('submit pressed');
e.preventDefault();
})
关于javascript - 为什么我的 localStorage.setItem() 和 localStorage.getItem() 没有存储值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59851688/