1

我在这里找到了许多计数器的解决方案,从一个总数到另一个动画。

这是我现在正在使用的:

jQuery.fn.extend({
          ts : function (from, to, time) {
            var steps = 1,
                self = this,
                counter;

            if (from - to > 0) {
              steps = -1;
            };

            from -= steps;

            function step() {
              self.text(from += steps);

              if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
                clearInterval(counter);
              };
            };

            counter = setInterval(step, time || 5);
          }
        });


        var total = $('.total').ts(56000,56941);

它运行良好,但是我想在总数中添加一个逗号,例如 56,941。这可能吗?

谢谢!

4

4 回答 4

1

我想这会做到:

jQuery.fn.extend({
    ts: function(from, to, time) {
        var steps = 1, self = this, counter;

        if (from - to > 0) steps = -1;
        from -= steps;

        function step() {
            var x = (from += steps).toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
            self.text(x);
            if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
                clearInterval(counter);
            };
        };
        counter = setInterval(step, time || 5);
    }
});

小提琴

于 2012-10-30T00:16:17.057 回答
1

从网络上的某个地方...

function formatComma(x){ 
    return (x+'').replace( /\B(?=(\d{3})+(?!\d))/g, ',');
}

我更喜欢我自己的反转字符串的解决方案,因为它更容易理解逻辑......

function formatComma(x){
    // prepare the input as a string ready for manipulating and returning
    return (x+'')
      // reverse the string (by converting to array)
      .split("").reverse().join("")
      // replace 3 digits in a row, with themselves and a comma
      // so long as the digits are followed by a non-word boundary
      .replace(/(\d{3})\B/g,'$1,')
      // reverse it all again
      .split("").reverse().join("")
}
于 2012-10-30T00:30:32.097 回答
0

是的!您可以检查此插件(http://code.google.com/p/jquery-numberformatter/)并在您的插件中实现它:-)

于 2012-10-30T00:09:05.780 回答
0

这将起作用。该函数取自http://ntt.cc/2008/04/25/6-very-basic-but-very-useful-javascript-number-format-functions-for-web-developers.html。非常便利

jQuery.fn.extend({
          ts : function (from, to, time) {
            var steps = 1,
                self = this,
                counter;

            if (from - to > 0) {
              steps = -1;
            };

            from -= steps;

            function step() {
              self.text(addCommas(from += steps));

              if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
                clearInterval(counter);
              };
            };

            counter = setInterval(step, time || 5);
          }
        });


var total = $('.total').ts(56000,56941);


function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

​</p>

于 2012-10-30T00:12:55.967 回答