2016-04-23 60 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选择元素。