简体   繁体   English

如何访问事件模板的dom元素?

[英]how to access a dom element of a template on events?

How to access element of a Template in meteor Template.name.events ? 如何在流星Template.name.events中访问模板的元素? here is an example of simple shopping-cart, 'qty' is not accessible in cart . 这是一个简单的购物车的示例,不能在cart中访问 “ qty”。

http://meteorpad.com/pad/nhgMaMKNMQEainhcY/Shopping%20cart http://meteorpad.com/pad/nhgMaMKNMQEainhcY/Shopping%20cart

Template 模板

<div class="col-sm-3">
   {{name}}
 </div>
 <div class="col-sm-3">
  ${{cost}}
 </div>
 <div class="col-sm-3">
  <input type="number" class="qty" length="3" min="1" max="5">
 </div>
 <div class="col-sm-3">
  <button class="btn btn-success add">Add</button>
 </div>

Template Event 模板事件

Template.productsList.events({
  'click .add': function (event) {
    cart.push(this); 
    console.log(cart);


  }

In Meteor, the this argument refers to the data context of the element that triggered the event. 在Meteor中, this参数是指触发事件的元素的数据上下文。 See here . 这里 Not to be confused with this in jquery events for example, which is a reference to the DOM element of invocation. 例如,不要在jquery事件中this混淆,它是对DOM调用元素的引用。 So you are able to access name , id and cost of every products . 因此,您可以访问每个products nameidcost If you want the value of your input, one way would be to use a form and send the whole form or to pass the template instance to the event and look it up in there, like so 如果要输入的值,一种方法是使用表单并发送整个表单,或将模板实例传递给事件并在其中查找,就像这样

Template.productsList.events({
  'click .add': function (event, template) {
    var qty = template.find('.qty').value;
    console.log(qty);
}

However, I do have to mention that this will go through the template and find the first element of class 'qty', which in your case of many elements with the same class will not get you to your goal. 但是,我确实要提到,这将遍历模板并找到类“ qty”的第一个元素,在您的情况下,如果有多个具有相同类的元素,则不会达到您的目标。 In your case you should use unique Id instead. 在您的情况下,您应该改用唯一ID。 Eg you could do this 例如,您可以这样做

<input type="number" class="qty" id="product_{{id}}" length="3" min="1" max="5">

and then 接着

var qty = template.find('#product_'+this.id).value;

in the event. 在事件中。 that oughta do it. 那应该做的。 let me know if it works for you. 请让我知道这对你有没有用。

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

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