【问题标题】:jQuery Counter Remains at "0" and doesn't count upjQuery Counter 保持在“0”并且不计数
【发布时间】:2022-01-11 00:58:34
【问题描述】:

我正在尝试使我网站的某个部分动画计数。但是,当我加载网站时,什么都没有运行,它仍然保持在“0”。我的 HTML 脚本开头有 jQuery <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');

  $({countNum: $this.text()}).animate({
      countNum: countTo
    },
    {
      duration: 8000,
      easing: 'linear',
      step: function() {
        $this.text(Math.floor(this.countNum));
      },
      complete: function() {
        $this.text(this.countNum);
        //alert('finished');
      }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="col-md-4 showinmbl">
  <h4 class="txt-primary  fs40 mb-0" class="counter" data-count="150" style="font-family: 'Inter', sans-serif; font-weight: 500;">0</h4>
  <p class="fs30 weight500" style="font-family: 'Inter', sans-serif; font-weight: 600;">Wins</p>
</div>

为什么不计算?

【问题讨论】:

  • 你的脚本出现在你的 HTML 之前还是之后 &lt;div&gt;?如果是之前,那么$(".counter") 将为空,代码不会做任何事情。
  • 使用浏览器的开发工具检查工具在控制台上查找错误。您需要等待加载内容,然后才能要求 JS/jquery 访问它,因此要么将您的 JS 放在最后,要么将其放在加载所有内容时运行的函数中。
  • @Pointy - 在我关闭正文标签之前,它就在文档的底部。
  • @AHaworth - 我的控制台中没有显示任何内容。
  • $({countNum: $this.text()}).animate?

标签: javascript html jquery css


【解决方案1】:

您在h4 标签中设置了两次class 属性。这就是为什么它不起作用。在此处查看此工作示例。

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');

  $({countNum: $this.text()}).animate({
      countNum: countTo
    },
    {
      duration: 8000,
      easing: 'linear',
      step: function() {
        $this.text(Math.floor(this.countNum));
      },
      complete: function() {
        $this.text(this.countNum);
        //alert('finished');
      }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="col-md-4 showinmbl">
  <h4 class="txt-primary  fs40 mb-0 counter" data-count="150" style="font-family: 'Inter', sans-serif; font-weight: 500;">0</h4>
  <p class="fs30 weight500" style="font-family: 'Inter', sans-serif; font-weight: 600;">Wins</p>
</div>

【讨论】:

    【解决方案2】:

    问题在于您的 HTML 代码。这一行:

      <h4 class="txt-primary  fs40 mb-0" class="counter" data-count="150" style="font-family: 'Inter', sans-serif; font-weight: 500;">0</h4>
    

    你已经设置了两次类属性,这是问题所在,你可以像这样改变你的 h4 标签,它会起作用:

      <h4 class="txt-primary fs40 mb-0 counter"  data-count="150" style="font-family: 'Inter', sans-serif; font-weight: 500;">0</h4>
    

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 2019-07-08
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 2016-05-11
      相关资源
      最近更新 更多