2016-06-11 53 views
0

我試圖用localStorage做一個簡單的待辦事項列表,但它不起作用。任何想法爲什麼?有時,當我瀏覽並返回已添加的項目時,我想知道這是否是我的瀏覽器(Chrome和Safari)上的簡單設置。爲什麼我的本地存儲不起作用?

function get_todos() { 
    var todos = new Array; 
    var todos_str = localStorage.getItem('todo'); 
    if (todos_str !== null) { 
     todos = JSON.parse(todos_str); 
    } 
    return todos; 
} 


function add() { 
    var task = document.getElementById('task').value; 
    var todos = get_todos(); 
    var newTask = { 
        name:task, 
        id: "item" + todos.length, 
        priority: { 
           isPriority:false, 
           color:"" 
           } 
       }; 

    todos.push(newTask); 
    localStorage.setItem('todo', JSON.stringify(todos)); 

    show(); 

    return false; 
} 


function remove() { 
    var id = this.getAttribute('id'); 
    var todos = get_todos(); 
    todos.splice(id, 1); 
    localStorage.setItem('todo', JSON.stringify(todos)); 

    show(); 

    return false; 
} 

function priority() { 
    var id = this.getAttribute('value'); 
    var todos = get_todos(); 

    for (var i=0;i<todos.length;i++) { 
    var todo = todos[i]; 
    console.log(todo); 
    if (todo.id==id) { 
     todo.priority.isPriority = true; 
     todo.priority.color = "red"; 
    } 
    } 

    localStorage.setItem('todo', JSON.stringify(todos)); 

    show(); 

    return false; 
} 

function show() { 
    var todos = get_todos(); 

    var html = '<p>'; 
    for (var i = 0; i < todos.length; i++) { 
    var todo = todos[i]; 
    html += "<p id='item" + i + "' isPriority='" + todo.priority.isPriority + "'>" + todo["name"] + '<p>' + "<button class='remove'>Delete</button>" + " " + "<button class='priority' value='item" + i + "'>Priority</button>"; 
    }; 


    document.getElementById('item').innerHTML = html; 

     var button1 = document.getElementsByClassName('priority'); 
     for (var i=0; i < button1.length; i++) { 
      button1[i].addEventListener('click', priority); 
     }; 

     var button2 = document.getElementsByClassName('remove'); 
     for (var i=0; i < button2.length; i++) { 
      button2[i].addEventListener('click', remove); 
     }; 
} 


document.getElementById('add').addEventListener('keyup', add); 
show(); 

http://codepen.io/kiddigit/pen/PzZgMQ

+0

不清楚具體問題是什麼。更詳細地解釋問題並在演示中重現步驟。你沒有解釋預期和實際行爲之間的差異 – charlietfl

回答

2

你的問題是,你是在按鈕結合的keyup代替click

document.getElementById('add').addEventListener('click', add); 

你可能會考慮包裝的形式輸入和按鈕:

<form id="add_form"> 
    <input id="task" type="text"> 
    <button id="add" type="submit">Add</button> 
</form> 

然後聽聽說MS submit事件:

document.getElementById('add_form').addEventListener('submit', function(event) { 
    event.preventDefault(); 
    add(); 
}); 

這樣進入將在輸入字段中正常工作。

+0

Jeez Louise,我很密集!優秀的幫助。非常感謝。 – Chris

+0

我很高興能幫到你!有時候你只需要打破所有的一部分,並檢查每個部分單獨工作,從外部開始:-) – andlrc