在每次迭代中使用jquery在一个手柄中选择元素

Select element with jquery inside a handlebars each iteration

本文关键字:元素 一个 选择 迭代 jquery      更新时间:2023-09-26

我正在做一个电子商店。我在HTML中显示一个产品列表,使用手柄。

对于每个元素,我都添加了一个按钮,允许用户在购物车中添加商品。它不工作,因为每次我点击按钮,我添加了所有的列表,而不仅仅是一个对象。

所以我知道我正在传递所有的列表(因为我传递'list'作为参数),我想知道如何只传递每个按钮的当前项。我不知道该怎么做。

html:

  <div class="container-fluid">
    <script id="list-items" type="text/x-handlebars-template">​
      {{#each list}}
        <div class="items col-lg-3 col-md-4 col-sm-6 col-xs-12">
          Category: {{ category}} </br>
          Name: {{ name }} </br>
          Price: {{ price }} </br>
          Quantity: {{ quantity }}
          <button class="addItem" class="btn">Buy</button>
        </div>
      {{/each}}
    </script>
  </div>
javascript:

var ShoppingCart = function () {
  this.cart = [];
};
ShoppingCart.prototype.addItem = function(item) {
  this.cart.push(item);
};

shoppingCart = new ShoppingCart();
$('.addItem').click(function() {
  shoppingCart.addItem(list);
});

在你的click函数中,你添加了整个列表:

shoppingCart.addItem(list);

并且您不需要转移要添加的整个项目。因为在作用域中已经有了整个列表,所以只需要让函数知道选择的索引是什么。可能的解决方案是在按钮id中添加把手索引,然后在jQuery中解析它,然后继续进行,或者考虑用纯javascript解决方案取代jQuery订阅点击事件的方式,并在把手的帮助下插入项目的索引,如下所示:

<button class="addItem" class="btn" onclick="addItem({{@index}})">Buy</button>

其中addItem为:

function addItem(index) {
  shoppingCart.addItem(list[index]);
}

我想你可以用一个项目ID(或索引)来排序:

<button id="{{ @index }}" class="addItem" class="btn">Buy</button>
$('.addItem').click(function() {
  shoppingCart.addItem(list[$(this).id]);
});