我在刷新页面时无法显示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 - 刷新页面时localStorage loadVote(损坏),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27449718/