【问题标题】:How do I add commas to this Javascript counter?如何在这个 Javascript 计数器中添加逗号?
【发布时间】:2021-02-24 07:43:42
【问题描述】:

我是 JS 的初学者,不知道如何在这里完成。想法是在数字中有逗号,以便在计数时更容易阅读,并且最终的静态结果也应该有逗号。

例如:“10,000”

var a = 0;
$(window).scroll(function() {

  var oTop = $('#counter').offset().top - window.innerHeight;
  if (a == 0 && $(window).scrollTop() > oTop) {
    $('.counter-value').each(function() {
      var $this = $(this),
        countTo = $this.attr('data-count');
      $({
        countNum: $this.text()
      }).animate({
          countNum: countTo
        },

        {

          duration: 2000,
          easing: 'swing',
          step: function() {
            $this.text(Math.floor(this.countNum));
          },
          complete: function() {
            $this.text(this.countNum);
            //alert('finished');
          }

        });
    });
    a = 1;
  }

});

【问题讨论】:

标签: javascript counter


【解决方案1】:

最好的方法是使用内置的 Intl 对象。更多信息here.

const number = 123456;
const formattedNumber = new Intl.NumberFormat('en-us').format(number);

console.log({ formattedNumber }); // 123,456

【讨论】:

  • @AdarshBhadauria ...您正在处理 jQuery 特定的 JS 代码。每次您想要或必须处理 jQuery 特定对象时都会发生值的美元函数包装,这是 jQuery 领域特定语言的一种可能入口。此类对象提供了大量方便的工具/流程,以便根据您的意愿弯曲(主要是 UI 特定的)JS 行为。在您的情况下,您只需将上述答案的代码 sn-p 复制到您唯一实际执行 UI 显示的方法中...complete: function() { $this.text(new Intl.NumberFormat('en-us').format(this.countNum)); }
猜你喜欢
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 2018-07-11
  • 2014-05-11
  • 1970-01-01
  • 2017-08-21
相关资源
最近更新 更多