【发布时间】:2014-12-23 05:16:44
【问题描述】:
我有一次用户投票 +1,现在我正在观看。刷新页面时我需要 loadVote,因为 saveVote 运行正常,我认为我的解决方案是返回投票; loadVote 函数。并且 saveVote(); 在哪里可以,在返回投票的一次或之后的函数中;
var voteUp = document.getElementById('vote-up');
var handUp = once(function() {
var total = Number(voteUp.innerHTML);
total += 1;
voteUp.innerHTML = total;
});
voteUp.addEventListener('click', handUp);
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context);
fn = null;
saveVote();
}
return result;
};
}
function saveVote() {
var votes = voteUp;
var data = Array.prototype.map.call(votes, function(vote){
return[vote];
});
localStorage.setItem('data', JSON.stringify(data));
console.log('saveVote');
}
function loadVote() {
var votes = JSON.parse(localStorage.getItem('data'));
if(!votes){
return;
}
Array.prototype.map.call(votes, function(vote){
return votes;
});
console.log(JSON.parse(localStorage.getItem('votes')));
}
loadVote();
【问题讨论】:
-
你通常通过记录服务器端的IP来解决这个问题,否则只需重新加载页面就会让某人多次投票。如果这不是问题,jQuery 有
one()! -
@adeneo 我将使用 localStorage 通过 JSON 保存和加载日期,但现在,“我需要投票一次”。因为现在我每次点击都可以无限投票。
标签: javascript jquery json local-storage addeventlistener