【问题标题】:jQuery number counter doesn't accept commasjQuery 数字计数器不接受逗号
【发布时间】:2018-11-07 22:52:14
【问题描述】:

我目前正在创建一个数字计数器(从 0 到一个值),如果它用逗号分隔,我在获取要呈现的数字时遇到了一些麻烦。

我找到了一些潜在的修复程序,例如 toLocaleString,但我无法让它工作 - 谁能指出我正确的方向?

目前当我使用 130,000 时,它返回 NaN。

谢谢!

$('.panel-text-style-c').each(function() {

  $(this).prop('Counter', 0).animate({
    Counter: $(this).text()
  }, {
    duration: 2000,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now).toString());
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='panel-text-style-c'>130,000</span>

以上内容

【问题讨论】:

  • 先用replace(',', '')去掉逗号。
  • @RoryMcCrossan,感谢您的回复 - 我将在哪里实施?抱歉有点困惑 - 再次感谢!
  • 我把它添加为你的答案

标签: javascript jquery


【解决方案1】:

在 JS 中,, 不能用于要解析为整数的值。这就是您收到NaN 输出的原因。

要解决此问题,请使用 replace() 删除逗号,然后再将其提供给 Counter 属性:

$('.panel-text-style-c').each(function() {
  $(this).prop('Counter', 0).animate({
    Counter: $(this).text().replace(/,/g, '')
  }, {
    duration: 2000,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now).toLocaleString());
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='panel-text-style-c'>130,000</span>

【讨论】:

  • 实现了这个之后,逗号又没有加进去,这可能吗?
  • 您可以在显示逻辑中使用toLocaleString()。我已经更新了答案,向您展示如何。请注意,如果您想强制逗号分组而不考虑语言环境,请使用this
  • 工作愉快,非常感谢你的朋友!!!一旦允许我将标记为正确答案!
  • 没问题,很高兴为您提供帮助
【解决方案2】:

试试这个代码:

$('.panel-text-style-c').each(function() {
  var num =   $(this).text().replace(',', '');
  
  $(this).prop('Counter', 0).animate({
    Counter: num
  }, {
    duration: 2000,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now).toString());
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='panel-text-style-c'>130,000</span>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    相关资源
    最近更新 更多