2
我想刪除數組中的項目,但它不會被刪除。我有該項目的ID,但我無法使用它。你能告訴我如何使用tasks
數組中的物品ID嗎?removeItem localStorage不起作用
function appendTaskToList(val, task_id) {
$('#list').append($("<li> <a href='#' class='done-btn'>Done</a>" +
" " + val + " <a href='javascript:void(0)' class='cancel-btn'>Delete</a></li>")
.data("task", task_id));
}
if (localStorage['tasks']) {
var tasks = JSON.parse(localStorage['tasks']);
for(var i=0;i<tasks.length;i++) {
appendTaskToList(tasks[i], i);
}
}else {
var tasks = [];
}
var addTask = function(){
var val = $('#name').val();
tasks.push(val);
var task_id = tasks.indexOf(val);
localStorage["tasks"] = JSON.stringify(tasks);
appendTaskToList(val, task_id);
$('#name').val("").focus();
};
$('#add-btn').click(addTask);
$('#name').keyup(function(e){
if (e.keyCode === 13) {
addTask();
}
});
$(document).delegate('.done-btn', 'click', function() {
$(this).parent('li').addClass('done');
return false;
});
我被困在這裏:
$(document).delegate('.cancel-btn', 'click', function(e) {
var task_elem = $(e.target).closest("li");
console.log(task_elem.data());
var taks_id = task_elem.data();
$(this).parent('li').remove();
localStorage.removeItem(tasks[taks_id]);
});
未捕獲的ReferenceError:()task_elem.data(1)TASK_ID沒有定義ı具有當我點擊刪除按鈕 –
tasks.splice此錯誤; localStorage.setItem('tasks',JSON.stringify(tasks));我使用這個代碼和繁榮!它的工作:)謝謝兄弟 –