我有一次用户投票+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();
答案 0 :(得分:2)
爱大卫沃尔什关于此HERE
的帖子function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
var voteUp = document.getElementById('vote-up');
var handUp = once(function() {
var total = Number(voteUp.innerHTML);
total += 1;
voteUp.innerHTML = total;
});
voteUp.addEventListener('click', handUp);
答案 1 :(得分:2)
只需这样做:
voteUp.addEventListener('click', function(){
//call your function method to what you want to do with voteUp
//and call this
this.removeEventListener('click');
});