添加onlick事件监听器看起来不工作js

时间:2018-05-08 11:49:23

标签: javascript mouseevent dom-events

这就是我的项目text-height的样子:

 html, body{
    height:100%;
    }

我在我的html标记中的每个项目上添加html然后我javascript我拿走了所有项目并尝试在我的每个项目上添加onclick事件但是idk为什么当我在每个加号减去按钮上计时时在任何项目上它只更改最后一项的值。

<div class="content__products__item" id="item1">
   <div class="content__products__item__picture">
      <a href="#"><img src="images/product-tea1.jpg"></a>
   </div>
   <div class="content__products__item__section">green tea</div>
   <div><a href="#" class="content__products__item__name">Loan si</a></div>
   <div class="content__products__item__price">
      <span>3.45</span> r
   </div>
   <div class="content__products__item__quantity clearfix">
      <button class="quantity-arrow-minus">-</button>
      <div class="quantity-num"><span>50</span> г</div>
      <button class="quantity-arrow-plus">+</button>
      <button class="quantity-add-to-basket">В корзину</button>
   </div>
   <div class="content__products__item__description-wraper">
      <div class="content__products__item__description">
         Good tea Good teaGood teaGood teaGood tea
      </div>
   </div>
</div>

请帮忙!

1 个答案:

答案 0 :(得分:0)

好的我这样做了:

var items = document.querySelectorAll('.content__products__item');

  items.forEach(function(item, i) {
    var btnMinus = document.querySelector('#item' + n + ' .quantity-arrow-minus');
    var btnPlus = document.querySelector('#item' + n + ' .quantity-arrow-plus');
    var input = document.querySelector('#item' + n + ' .quantity-num span');
    var currentPrice = document.querySelector('#item' + n + ' .content__products__item__price span');
    var pricePerGram = currentPrice.textContent / 50;
    btnPlus.onclick = function(e) {
      input.textContent = +input.textContent + 50;
      currentPrice.textContent = (+input.textContent * pricePerGram).toFixed(2);
    }
     btnMinus.onclick = function(e) {
       if(input.textContent > 50) {
       input.textContent = +input.textContent - 50;
      currentPrice.textContent = (+input.textContent * pricePerGram).toFixed(2);
       }
    }
  });

现在它运作良好!