2016-04-23 37 views
1

我正在通過David Turnbull的第二個Meteor App(待辦事項列表應用程序)教程,並且針對類似事件使用了不同的jquery語法,我不太明白爲什麼。 ..event.target jquery:語法差異

第一部分涉及功能添加任務:

HTML:

<template name="addTodo"> 
<form> 
Create a task: 
<input type="text" placeholder="Type a task here..." name="todoName" autocomplete="off"> 
</form> 
</template> 

JS:

Template.addTodo.events({ 
'submit form': function(event){ 
    event.preventDefault(); 
    var todoName = $('[name="todoName"]').val(); 
    Todos.insert({ 
    name: todoName, 
    completed: false, 
    createdAt: new Date() 
    }); 
} 
}); 

HTML:

<template name="todos"> 
{{> addTodo}} 
<ul> 
{{# each todo}} 
    {{> todoItem}} 
{{/each}} 
</ul> 
</template> 

<template name="todoItem"> 
<li> 
    <input type="text" value="{{name}}" name="todoItem"> 
</li> 
</template> 

JS:

第二部分通過使用KEYUP功能包括編輯任務

Template.todoItem.events({ 
'keyup [name=todoItem]': function(event){ 
    var documentId = this._id; 
    var todoItem = $(event.target).val(); 
    Todos.update({ _id: documentId }, {$set: {name: todoItem }}); 
    } 
}); 

我試圖在第二部分使用下面的event.target查詢(編輯任務),但它不起作用:

var todoItem = $('[name="todoItem"]').val(); 

這是爲什麼?我們在哪些情況下使用哪些?

回答

0

您有多個todoItems,它們都具有相同的名稱。相反,嘗試event.target.inputName.value沒有jQuery。

//event 
Template.todoItem.events({ 
    'keyup [name=todoItem]': function(event){ 
     var documentId = this._id; 
     var todoItem = event.target.todoItem.value; 
     Todos.update({ _id: documentId }, {$set: {name: todoItem }}); 
    } 
}); 

如果它不起作用,可能是因爲您的輸入沒有唯一的id/class。如果你用<form></form>(event.target)代替<li></li>,但它不應該認爲它是最好的解決方案。我可能會將每個任務的ID添加到<input>,如id="{{_id}}",並使用該ID選擇元素。