2013-02-21 33 views
1
function Todo(id, task, who, dueDate) { 
    this.id = id; 
    this.task = task; 
    this.who = who; 
    this.dueDate = dueDate; 
    this.done = false; 
} 


function updateDone(e) { 
     var spanClicked = e.target; 
     var id = spanClicked.parentElement.id; 
     spanClicked.innerHTML = " ✔ "; 
     spanClicked.setAttribute("class", "done"); 
     console.log("you clicked this span" + id); 


     for(var i = 0; i < todos.length; i++) { 
     if (todos[i].id == id) { 
      var mark = todos[i]; 
      mark.setAttribute("class", "done"); 
      console.log(mark); 
      break; 
      } 
      } 
    } 

此問題的第一部分更新網頁以顯示對象已「完成」。第二部分是我遇到問題的地方。我試圖更新數組內的「完成」的對象。這個想法是將用戶點擊的id與數組中的id相匹配,然後使用setAttribute將其設置爲「完成」。然而,我得到的console.log(標記)控制檯消息是mark.setAttribute不是一個函數。有關如何修改此內容以便我可以將數組中的對象更新爲「已完成」的任何建議?setAttribute

+0

如果試圖更改類,使用'element.className = 「完成」'。 – 2013-02-21 18:43:11

+2

你能說明'todos'是如何填充的嗎?它是一個元素的數組還是僅僅是ID? – hexblot 2013-02-21 18:44:27

+0

謝謝你添加了另一個類「完成」,但它不會改變已經存在的類。 – user2084813 2013-02-21 18:46:30

回答

0
for(var i = 0; i < todos.length; i++) { 
    if (todos[i].id == id) { 
     var element = document.getElementById(todos[i].id); 
     element.setAttribute("class", "done"); 
     console.log(element); 
     break; 
    } 
} 

,或者「標記」在你的例子不是一個DOM對象,那麼你只需設置它完成屬性爲true。

for(var i = 0; i < todos.length; i++) { 
    if (todos[i].id == id) { 
     todos[i].done = true; 
     console.log(todos[i]); 
     break; 
    } 
} 
0

使用setAttribute設置類不是一個好主意。

//Works with FF and Chrome 
obj.setAttribute("class", "done"); 

//works with IE 
obj.setAttribute("className", "done"); 

//works with all browsers 
obj.className = "done";