Jquery数字计数器组合在一起

时间:2017-01-09 14:57:30

标签: javascript jquery regex

我得到了这些数字,但字母是" T"已被替换,以便它不会显示。你们有没有想过如何让它发挥作用。非常感谢你。



function commaSeparateNumber(val){
   while (/(\d+)(\d{3})/.test(val.toString())){
     val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
   }
   return val;
 }

$('.number').each(function () {
  $(this).prop('Counter',0).animate({
      Counter: $(this).text()
  }, {
      duration: 8000,
      easing: 'swing',
      step: function (now) {
          $(this).text(commaSeparateNumber(Math.ceil(now)));
      }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<div class="count"><div class="number">30</div></div>
<div class="text">text 1</div>
</div>
<div class="col-md-4">
<div class="count"><div class="number">3000</div></div>
<div class="text">text 2</div>
</div>
<div class="col-md-4">
<div class="count"><div class="number">700<span>T</span></div></div>
<div class="text">text 3</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您的代码的问题是它正在替换整个DOM结构包括包含'T'的span,因此DOM结构已更新。 这是您更新的代码

function commaSeparateNumber(val){
   while (/(\d+)(\d{3})/.test(val.toString())){
     val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
   }
   return val;
 }

$('.number').each(function () {
  $(this).prop('Counter',0).animate({
      Counter: $(this).text()
  }, {
      duration: 8000,
      easing: 'swing',
      step: function (now) {
          $(this).text(commaSeparateNumber(Math.ceil(now)));
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<div class="count"><div><span class="number">30</div></div>
<div class="text">text 1</div>
</div>
<div class="col-md-4">
<div class="count"><div><span class="number">3000</span></div></div>
<div class="text">text 2</div>
</div>
<div class="col-md-4">
<div class="count"><div><span class="number">700</span><span>T</span></div></div>
<div class="text">text 3</div>