gpt4 book ai didi

javascript - 所有事件的本地存储

转载 作者:行者123 更新时间:2023-12-03 08:59:37 28 4
gpt4 key购买 nike

   function pushButton(buttonValue) {
if (buttonValue == 'C') {
document.getElementById('screen').value = '0';
}
else {//this is where most changes occured
var x= document.getElementById('screen').value
x =parseInt(x)+ parseInt(buttonValue);
document.getElementById('screen').value=x;
localStorage.setItem('answer', x);
}
}

function calculate(equation) {
var answer = eval(equation);
document.getElementById('screen').value = answer;
}

HTML:

<table class="calc" cellpadding=2>
<td><input type="button" class="calc" id="screen" value="0" ></td>
<tr>
</table>
<table class="calc" cellpadding=2>
<td><button type="button" onclick="pushButton(1)" value="Call2Functions">1</td>
<td><button type="button" onclick="pushButton(2)" value="Call2Functions">2</td>
<td><button type="button" onclick="pushButton(3)" value="Call2Functions">3</td>
<td></td>
</tr>
<div>

即使在尝试此代码后,我也无法在本地存储值。请问有人可以帮助我吗?我仍然在寻找这个问题的解决方案..添加 localStorage 后我也无法在本地存储值 请帮助我,我已经尝试了很多...

最佳答案

要将项目存储在 localStorage 中,您需要使用 localStorage.setItem 存储与键配对的值:

var key = 'yourKey'
, resultToStore = 'test';
localStorage.setItem(key, resultToStore);

要检索值,只需调用 localStorage.getItem 并传入 key 即可:

var returnedResult = localStorage.getItem(key);

在您的函数 pushButton 中,您需要存储该值:

function pushButton(buttonValue) {
if (buttonValue == 'C') {
document.getElementById('screen').value = '0';
}
else {//this is where most changes occured
var x= document.getElementById('screen').value
x =parseInt(x)+ parseInt(buttonValue);
document.getElementById('screen').value=x;
localStorage.setItem('answer', x);
}
}

现在,每当页面加载时,您都需要查看 localStorage 中是否有值,如果存在则获取该值:

window.onload = function() {
var oldAnswer = localStorage.getItem('answer');
if(oldAnswer) {
document.getElementById('screen').value = oldAnswer;
}
}

关于javascript - 所有事件的本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32350438/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com