简体   繁体   English

$(e.target).find 和 template.find('input').value 有什么区别

[英]Whats the difference between $(e.target).find and template.find('input').value

Its probably something basic but wanted explanation of the use cases.它可能是一些基本但想要解释用例的东西。 Like sometimes hitting "enter" inputs the data, while sometimes mouseclicks work.就像有时点击“输入”输入数据,而有时鼠标点击工作。 I'm concerned about "Gotchas" that I would have overlooked.我担心我会忽略的“陷阱”。 Like maybe it works in Firefox but not in Chrome for example.例如,它可能适用于 Firefox,但不适用于 Chrome。

I saw the following 2 ways, both are ways to input data into a form element.我看到了以下两种方式,都是将数据输入到表单元素中的方式。

First way第一种方式

JavaScript JavaScript

var $body = $(e.target).find('[name=body]');  //defines the content
var comment = { body: $body.val() };    

HTML HTML

<form class="form-send-message" id="addcomment" data-keyboard-attach>
  <textarea id="body" name="body"></textarea>
</form>

Second way第二种方式

JavaScript JavaScript

var message = template.find('input').value;

HTML HTML

<form class="message" data-keyboard-attach>
    <input type="text" name="body" id="body">
    <button class="icon" type="submit"></button> 
</form>

Here you can see two ways to find the value of an input/textarea with an explanation:在这里,您可以看到两种查找 input/textarea 值的方法,并附有说明:

'submit .new-post': function(event){
    //returns name="postBody" content from the form you're submitting
    var postBody = event.target.postBody.value;  

    //returns the value of an html element that exists in DOM, even if its inside a different template or form.
    var postBody = $('.someClass').val()  
}

Your first code Is jQuery , while your second code is Meteor .您的第一个代码是jQuery ,而您的第二个代码是Meteor They both can accomplish the same thing under the right circumstances.他们都可以在适当的情况下完成同样的事情。 Also, according to this answer , meteor's template.find is an alias for jQuery's $ , meaning they are the exact same.此外,根据此答案,meteor 的template.find是 jQuery 的$的别名,这意味着它们完全相同。

But, the codes don't do the same thing in this case.但是,在这种情况下,代码不会做同样的事情。

Your first code finds the value an element with a name of "body" inside e.target .您的第一个代码在e.target找到名称为“body”的元素的值。 I am assuming e is an Event , but there is no way to tell with the current amount of code you gave.我假设e是一个Event ,但是无法用您提供的当前代码量来判断。

The second code just gets the value of the first INPUT element it finds.第二个代码只是获取它找到的第一个 INPUT 元素的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM