带有Jquery变量的Foreach循环

时间:2018-06-16 11:53:20

标签: javascript php jquery foreach counter

我有以下代码:

HTML:

<div class="single-count_contain">
<div class="less"><img src="img/single_arrow_left.png"></div>
<div class="theCount">1</div>
<div class="add"><img src="img/single_arrow_right.png"></div>
</div>

JS:

var counter = 1;

$(".add").click(function(){

counter++;

$(this).closest(".single-count_contain").find(".theCount").text(counter);

});


$(".less").click(function(){

 counter--;

$(this).closest(".single-count_contain").find(".theCount").text(counter);

});  

这可以按预期工作,递增和递减我的计数器变量。但我需要在foreach循环中使用它。

我怎样才能拥有相同的变量,但每个计数器生成的结果不同但是foreach循环?

谢谢!

1 个答案:

答案 0 :(得分:0)

鉴于count元素将始终包含一个值,最简单的方法是读取count元素的文本,将其解析为整数并更新它。

e.g。

$(".add").click(function() {

  var $count = $(this).closest(".single-count_contain").find(".theCount");
  $count.text(parseInt($count.text()) + 1);

});

$(".less").click(function() {

  var $count = $(this).closest(".single-count_contain").find(".theCount");
  $count.text(parseInt($count.text()) - 1);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="single-count_contain">
  <div class="less"><img src="img/single_arrow_left.png"></div>
  <div class="theCount">1</div>
  <div class="add"><img src="img/single_arrow_right.png"></div>
</div>

<div class="single-count_contain">
  <div class="less"><img src="img/single_arrow_left.png"></div>
  <div class="theCount">1</div>
  <div class="add"><img src="img/single_arrow_right.png"></div>
</div>

您还可以使用.siblings()函数选择计数元素。

e.g。

var $count = $(this).siblings(".theCount");

<强>更新

要更新数据计数器值,您可以执行以下操作:

var count = parseInt($count.text()) + 1;
$count.text(count).data("counter", count);

另一种解决方案

$(".single-count_contain").each(function() {
  var counter = 1;
  
  $(this).on("click", ".less,.add", function() {
    if ($(this).hasClass("less"))
      counter--;
    else
      counter++;

    $(this).siblings(".theCount").text(counter).data("counter", counter);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="single-count_contain">
  <div class="less"><img src="img/single_arrow_left.png"></div>
  <div class="theCount">1</div>
  <div class="add"><img src="img/single_arrow_right.png"></div>
</div>

<div class="single-count_contain">
  <div class="less"><img src="img/single_arrow_left.png"></div>
  <div class="theCount">1</div>
  <div class="add"><img src="img/single_arrow_right.png"></div>
</div>