$(function () {
let dataArr = JSON.parse(localStorage.getItem('todolist')) || []
load()
function load() {
$('.todo-list').empty()
dataArr.forEach(function (obj, index) {
let theLi = $(`<li class=${obj.done?'completed':'' }>
<input class="toggle" type="checkbox" ${obj.done ? 'checked' : ''}>
<label>${obj.info}</label>
<button class="destroy" idx=${index}></button>
</li>`)
$('.main .todo-list').prepend(theLi)
})
}
$('.header .new-todo').on('keyup', function (e) {
if (e.keyCode === 13 && $(this).val().trim().length > 0) {
let val = $(this).val()
let newObj = {
info: val,
done: false
}
dataArr.push(newObj)
$(this).val('')
localStorage.setItem('todolist', JSON.stringify(dataArr))
load()
}else if(e.keyCode === 13 && $(this).val().trim().length===0 ){
alert('任务名称不能为空')
}
})
$('.todo-list').on('click', '.destroy', function () {
let index = $(this).attr('idx')
dataArr.splice(index, 1)
save()
load()
})
$('.todo-list').on('click', '.toggle', function () {
let index = $(this).siblings('button').attr('idx')
dataArr[index].done = !dataArr[index].done
$(this).parent().toggleClass('completed')
save()
load()
})
function save() {
localStorage.setItem('todolist', JSON.stringify(dataArr))
}
});