我的jquery计数器正在混合元素-为什么?

时间:2019-01-17 23:19:51

标签: javascript jquery html css

我有一个小的html页面,其中包含充满货币值的表。

   TEXT     |   SUM    |   LIMIT  |
-----------------------------------
Text One    |   1.700 €|   1.500 €|
Text Two    |   1.945 €|   2.000 €|

html:

<tr><td>Text One</td><td class="text-right text-nowrap"><label class="euro counter" target="1200" limit="1500"></label></td><td class="text-right text-nowrap"><label class="euro">1.500</label></td></tr>
<tr><td>Text Two</td><td class="text-right text-nowrap"><label class="euro counter" target="2345" limit="2000"></label></td><td class="text-right text-nowrap"><label class="euro">2.000</label></td></tr>

然后,我添加了一个jQuery计数器,该计数器最多可以计数到目标值。
这很好。但是我还想添加一个条件,如果该值大于限制,则该值将变为红色。但计数器会同时使用这两个值,并且在达到第一个LIMIT 1.500之后,SUM会变为红色。 如何以通用方式分离所有值? 这是js代码:

$(document).ready(function(){
  $('.counter').each(function() {
    var $this = $(this),
        target = $this.attr('target');
        limit = $this.attr('limit');
    $({ countNum: $this.text()}).animate({
      countNum: target
    },
    {
      duration: target*2,
      easing:'swing',
      step: function() {
        if (parseInt($this.text(), 10) > limit) {
          console.log($this.text());
          $this.addClass('f-red');
        }
        $this.text(Math.floor(this.countNum));
      }
    });
  });
});


编辑:在表格示例中-我只想以红色显示第一个SUM值,但是我的实际计数器代码以红色显示两个SUM值,因为这两个值均高于最小限制(1.500)。如何为每行设置单独的限制?

1 个答案:

答案 0 :(得分:1)

它不起作用,因为您不能使用变量,并且期望它在同步使用它时具有不同的值。

确切地说,足以更改此行

if (parseInt($this.text(), 10) > limit) {

if (parseInt($this.text(), 10) > $this.attr('limit')) {

始终与实际限制进行比较

http://jsfiddle.net/umdnq38t/