【问题标题】:JQuery Animate function not working commas/decimalsJQuery Animate 函数不工作逗号/小数
【发布时间】:2020-01-16 01:51:57
【问题描述】:

这是我的 HTML:

<li class="mega-menu-counter mega-menu-item mega-menu-item-type-post_type mega-menu-item-object-page mega-align-bottom-left mega-menu-flyout mega-menu-item-12028 menu-counter" id="mega-menu-item-12028">
   <a class="mega-menu-link" href="https://createandgo.com/blog-income-report/" tabindex="0">August 2019 <div>$<span class="counter">111,926.06</span></div><div>Blog Income Report</div></a>
</li>

这是我的 JavaScript:

<script>
$('.Count').each(function () {
  var $this = $(this);
  jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
    duration: 1000,
    easing: 'swing',
    step: function () {
      $this.text(this.Counter.toFixed(2));
    }
    }
  });
});
</script>

我的网站头部加载了以下资源:

<script
  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-animateNumber/0.0.14/jquery.animateNumber.min.js"></script>

谁能告诉我为什么计数器不工作?enter image description here

【问题讨论】:

  • html 中没有类 "Count"$('.Count') 匹配。看起来像是错字,您应该改用 ".counter" 类选择器

标签: javascript jquery wordpress jquery-animate jquery-countdown


【解决方案1】:
  • replace(/,/g, '') - 将货币格式转换为数字格式

  • toLocaleString(...) - 将数字转换为货币格式

$('.count').each(function() {
  var $this = $(this);
  jQuery({
    Counter: 0
  }).animate({
    Counter: $this.text().replace(/,/g, '')
  }, {
    duration: 1000,
    easing: 'swing',
    step: function() {
      $this.text(toCurrencyFromat(this.Counter));
    },
    complete: function() {
      $this.text(toCurrencyFromat(this.Counter));
    }
  });
});

function toCurrencyFromat(num) {
  return (num).toLocaleString('en-US', {
    currency: 'USD',
    maximumFractionDigits: 2
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-animateNumber/0.0.14/jquery.animateNumber.min.js"></script>

<li class="mega-menu-counter mega-menu-item mega-menu-item-type-post_type mega-menu-item-object-page mega-align-bottom-left mega-menu-flyout mega-menu-item-12028 menu-counter" id="mega-menu-item-12028">
  <a class="mega-menu-link" href="https://createandgo.com/blog-income-report/" tabindex="0">August 2019 <div>$<span class="count counter">111,926.06</span></div><div>Blog Income Report</div></a>
</li>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多