setTimeout如何为选择表单输入保存和加载数据?我试图让它与事件监听器一起工作。我检查了捕获&泡沫,我仍然试图包裹我的脑袋。
我需要它来设置或获取从输入字段分配给各个元素的值,具体取决于字段上是否有焦点或模糊等变化。
我错过了哪个功能或步骤,我应该从哪里开始寻找?
answers = document.getElementsByName('answers[]');
for(var i = 0; i < answers.length; i++) {
nodeIndex = 'answer' + i;
if(answers[i] == ''){
answers[i].addEventListener('blur', function(){
localStorage.setItem(nodeIndex, answers[i].value);
});
}
else {
answers[i].addEventListener('focus', function(){
answers[i].value = localStorage.getItem(nodeIndex);
localStorage.setItem(nodeIndex, answers[i].value);
});
answers[i].addEventListener('blur', function(){
localStorage.setItem(nodeIndex, answers[i].value);
answers[i].value = localStorage.getItem(nodeIndex);
});
} // end if
} // end forloop
REVISED 我注意到只有最后一个元素受到影响。当我在答案[0]中输入文本到答案[14]时,它们的值被保存并设置/复制到最后一个元素。我怎么用错了?我读了,似乎遵守规则......
function processAnswers(i, answers) {
setTimeout(function() {
nodeIndex = 'answer' + i;
if(localStorage.getItem(nodeIndex) === null) {
answers[i].addEventListener('blur', function(){
localStorage.setItem(nodeIndex, answers[i].value);
});
} // end if
else {
answers[i].addEventListener('focus', function(){
answers[i].value = localStorage.getItem(nodeIndex);
localStorage.setItem(nodeIndex, answers[i].value);
});
answers[i].addEventListener('blur', function(){
localStorage.setItem(nodeIndex, answers[i].value);
answers[i].value = localStorage.getItem(nodeIndex);
});
} // end else
}, 100); // end setTimeout()
} // end processAnswers();
answers = document.getElementsByName('answers[]');
for(var i = 0; i < answers.length; i++) {
processAnswers(i, answers);
}
我的代码失控了。我决定重新开始并保持简单......它有效!
var answers;
var clearAnswersBtn;
var clearAnswers;
var MainLoop = function MainLoopFunction(){
answers = document.getElementsByName('answers[]');
clearAnswersBtn = document.getElementsByTagName('body')[0];
clearAnswersBtn.innerHTML = clearAnswersBtn.innerHTML + '<button id="clearanswers" style="position:fixed;bottom:0;right:0;padding:5px;margin:0 10px 10px 0;z-index:99999">Clear Saved Answers</button>';
clearAnswers = document.getElementById('clearanswers');
clearAnswers.addEventListener("click", function(){
localStorage.clear();
alert("Answers Cleared!");
});
function saveAnswers(i, answer){
if(localStorage.getItem(i)) {
answer.value = localStorage.getItem(i);
}
else {
answer.addEventListener("blur", function(){
if(!localStorage.getItem(i)) {
localStorage.setItem(i, answer.value);
}
});
}
} // end saveAnswers()
setTimeout(function(){
for( var i = 0; i < answers.length; i++) {
saveAnswers(i, answers[i]);
}
}, 0)
}();