jQuery按顺序迭代整数

时间:2019-05-29 11:08:53

标签: javascript jquery html

我做了什么,根据自己的属性在元素上有序地迭代整数。但是顺序不对,已经将css order设置为像2,3,5这样的元素,但是我想忽略那些在迭代时没有属性的元素。

var i = 0;
jQuery('.each-order').each(function() {
  i++;

  if (jQuery(this).attr('data-payment') === '1') {
    console.log(i);
    jQuery(this).css('order', i);
  }
});
#orders {
  display: flex
}

.each-order {
  border: 1px solid red;
  padding: 10px;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="orders">
  <div class=each-order data-payment="0">Test 1</div>
  <div class=each-order data-payment="1">Test 2</div>
  <div class=each-order data-payment="1">Test 3</div>
  <div class=each-order data-payment="0">Test 4</div>
  <div class=each-order data-payment="1">Test 5</div>
</div>

已经输出:

<div id="orders">
  <div class="each-order" data-payment="0">Test 1</div>
  <div class="each-order" data-payment="1" style="order: 2;">Test 2</div>
  <div class="each-order" data-payment="1" style="order: 3;">Test 3</div>
  <div class="each-order" data-payment="0">Test 4</div>
  <div class="each-order" data-payment="1" style="order: 5;">Test 5</div>
</div>

期望输出:

<div id="orders">
  <div class="each-order" data-payment="0">Test 1</div>
  <div class="each-order" data-payment="1" style="order: 1;">Test 2</div>
  <div class="each-order" data-payment="1" style="order: 2;">Test 3</div>
  <div class="each-order" data-payment="0">Test 4</div>
  <div class="each-order" data-payment="1" style="order: 3;">Test 5</div>
</div>

1 个答案:

答案 0 :(得分:2)

如果不使用,请不要增加i

var i = 0;
jQuery('.each-order').each(function() {
  if (jQuery(this).attr('data-payment') === '1') {
    jQuery(this).css('order', ++i); // Prefix increment, only if you use it
  }
});

更新的代码段:

var i = 0;
jQuery('.each-order').each(function() {
  if (jQuery(this).attr('data-payment') === '1') {
    jQuery(this).css('order', ++i); // Prefix increment, only if you use it
  }
});
#orders {
  display: flex
}

.each-order {
  border: 1px solid red;
  padding: 10px;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="orders">
  <div class=each-order data-payment="0">Test 1</div>
  <div class=each-order data-payment="1">Test 2</div>
  <div class=each-order data-payment="1">Test 3</div>
  <div class=each-order data-payment="0">Test 4</div>
  <div class=each-order data-payment="1">Test 5</div>
</div>