我正在尝试使用本地存储构建一个小型 Web 应用程序。我可以添加和删除项目,但编辑项目工作到一定程度。项目按照您的预期进行编辑,但是当您更新(刷新)页面时,我得到一个额外的项目和一个空项目。我想我快到了,但无法解决这个问题。请看我的小提琴:http: //jsfiddle.net/willwebdesigner/786Qu/2/
$(document).ready(function() {
var i = 0;
var menuButtons = " <a class='delete' href='#'>delete</a> <a class='edit' href='#'>edit</a></li>";
// Initial loading of tasks
for( i = 0; i < localStorage.length; i++) {
$("#tasks").append("<li id='task-" + i +"'>" + localStorage.getItem('task-' + i) + menuButtons);
}
// Add a task
$("#tasks-form").submit(function() {
if ( $("#task").val() != "" ) {
localStorage.setItem( "task-" + i, $("#task").val());
$("#tasks").append("<li id='task-" +i +"'>"+localStorage.getItem("task-" + i) + menuButtons);
$("#task-" + i).css('display', 'none');
$("#task-" + i).slideDown();
$("#task").val("");
i++;
}
return false;
});
// Remove a task
$(document).on("click", "#tasks li a.delete", function() {
localStorage.removeItem($(this).parent().attr("id"));
$(this).parent().slideUp('slow', function() {
$(this).remove();
});
// This part resets all the IDs
for( i = 0; i < localStorage.length; i++) {
if( !localStorage.getItem("task-"+ i)) {
localStorage.setItem("task-"+ i, localStorage.getItem('task-' + (i + 1) )); // Moves the id up a level
localStorage.removeItem("task-"+ (i + 1) ); // Removes the id 1 up from the deleted item
}
}
});
// Edit a task
$(document).on("click", "#tasks li a.edit", function() {
var thisID = $(this).parent().attr("id");
$(this).parent().html("<form><input class='taskEdit" + thisID + "' autofocus><input type='submit'></form>")
.submit(function() {
localStorage.removeItem("task-" + thisID);
localStorage.setItem("task-" + thisID, $(".taskEdit" + thisID ).val());
$(this).html(localStorage.getItem("task-" + thisID) + menuButtons);
return false;
});
});
// Reset all
$("#reset").click(function() {
localStorage.clear();
});
});
感谢您的关注!