gpt4 book ai didi

javascript - 刷新页面时本地存储加载投票(损坏)

转载 作者:行者123 更新时间:2023-11-28 15:30:48 28 4
gpt4 key购买 nike

当我刷新页面时,我无法显示 voteUp/Down,因为如果我执行 voteUp/Down(+1 或 -1) 并刷新页面,这会再次返回 voteUp/Down (0)。过去我使用 JSON,但社区推荐不使用 JSON。所以我在这一刻拥有了它。谢谢。

    var voteUp = document.getElementById('vote-up');
var voteDown = document.getElementById('vote-down');

var handUp = once(function() {
var total = Number(voteUp.innerHTML);
total += 1;
voteUp.innerHTML = total;
saveVote();
});

voteUp.addEventListener('click', handUp);

var handDown = once(function() {
var total = Number(voteDown.innerHTML);
total -= 1;
voteDown.innerHTML = total;
saveVote();
});

voteDown.addEventListener('click', handDown);

function once(fn, context) {
var result;

return function() {
if(fn) {
result = fn.apply(context);
fn = null;
}
return result;
};
}

function saveVote() {
var votes = voteUp, voteDown;
localStorage.setItem('data', votes);
console.log('saveVote');
}

function loadVote() {
var votes = localStorage.getItem('data');
if(!votes){
return;
}
console.log(localStorage.getItem('data'));
}

loadVote();

最佳答案

var voteUp = document.getElementById('vote-up');

function handUp() {
var total = Number(voteUp.innerHTML);
total += 1;
voteUp.innerHTML = total;
}

voteUp.addEventListener('click',handUp,false);

它通过单​​击来增加每个值。

关于javascript - 刷新页面时本地存储加载投票(损坏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449718/

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