我的小应用程序有问题, 你可以在这里看到它:http://jsfiddle.net/47bV8/
我的问题是:当我“全部清除”时,我会输入一些注释,然后我重新输入一个注释, 控制台在刷新时返回lsReturn == null。
我理解为什么但看不出如何解决问题。
事实上,在清除全部之后我的'var i'的值不是0(它的值是我输入的最后一个音符,所以如果我输入了5个音符则为5),所以当我重新输入音符时它的任务-6,所以在刷新时我的第一个循环失败了......
我试图在localstorage.clear之后设置var i = 0,但它没有工作......
jQuery(document).ready(function() {
// Initial loading of tasks
var i = 0;
// clear All
jQuery('.clear').on('click',function(e){
e.preventDefault();
jQuery('#tasks li').remove();
localStorage.clear();
jQuery(this).data('erase', true);
});
if(localStorage.length){
for( i = 0; i < localStorage.length; i++){
var lsReturn = JSON.parse(localStorage.getItem('task-'+i));
if (lsReturn == null){ // HERE IS THE PROBLEM
var b = 0; //
}else{
jQuery("#tasks").append("<li id='task-"+i+"'>" + lsReturn.text + " <a href='#'>Delete</a></li>");
jQuery('#tasks li#task-'+i+'').css('background-color', lsReturn.color );
}
}
}else{
jQuery('header').after("<p class='error'>no messages</p>");
}
// ----------------- ADD A TASK ----------------------//
jQuery("#tasks-form").submit(function() {
if (jQuery("#task").val() != "" ) {
jQuery('#task').attr('placeholder', "Enter a note")
var text = jQuery("#task").val();
var color = jQuery('#color').val();
var allNotes = {};
var note = {};
note.text = text;
note.color = color;
allNotes['task-'+i] = note;
var lsStore = JSON.stringify(allNotes['task-'+i ]);
localStorage.setItem( "task-"+i, lsStore);
var lsStoreReturn = JSON.parse(localStorage.getItem("task-"+i, lsStore));
jQuery("#tasks").append("<li id='task-"+i+"'>"+ lsStoreReturn.text +"<a href='#'>Delete</a></li>");
jQuery('#tasks li#task-'+i+'').css('background-color', lsStoreReturn.color );
jQuery("#task").val("");
i++;
}else{
jQuery('#task').attr('placeholder', "nothing in it !")
}
return false;
});
// ----------------- REMOVE A TASK ----------------------//
jQuery("#tasks li a").live("click", function(e) {
e.preventDefault();
localStorage.removeItem(jQuery(this).parent().attr("id"));
jQuery(this).parent().remove();
// PROBLEM solved : if I remove a task #2 in a list of 4 item for example, if i refresh the list become 0, 1, 3, 4,
// so the locastorage loop doesn't find the item 2
for(i=0; i<localStorage.length; i++) { // SO I check my locastorage
if(localStorage.getItem("task-"+i) == null) { // If the task 4 doesn't exist
localStorage.setItem("task-"+i, localStorage.getItem('task-' + (i+1)));
// I do : create task-4
// and give him the value of task 5
localStorage.removeItem('task-'+ (i+1) );
// the i remove task 5
// so the loop wiil not find task 5 and give him the value of task 6 etc..
}
}
});
});
答案 0 :(得分:0)
按以下方式重置i
变量
jQuery('.clear').on('click',function(e) {
e.preventDefault();
jQuery('#tasks li').remove();
localStorage.clear();
jQuery(this).data('erase', true);
// Need to reset the index counter here.
i = 0;
});
以下是更新/工作fiddle。