JS数字计数器只能工作一次

时间:2014-08-28 19:20:16

标签: javascript jquery

所以我的计数器第一次工作。 再次单击按钮我需要继续计数,但是第一次运行后功能不起作用,有人知道怎么做吗?

我的jsFiddle:http://jsfiddle.net/wtkd/xpqg0fa9/

如果你不想在jsFiddle中看到我的js:

window.Fighters = (function() {
  var padNum;

  function Fighters(options) {
    var random;
    this.greenFighter = $('.green-fighter');
    this.blueFighter = $('.blue-fighter');
    this.team = $('.green-team, .blue-team');
    this.thumb = $('.thumb');
    random = Math.ceil(Math.random() * 301232);
    $('.punch1').on('click', (function(_this) {
      return function(e) {
        return _this.countUp(random, '.right-counter span', 2222);
      };
    })(this));
    $('.punch2').on('click', (function(_this) {
      return function(e) {
        return _this.countUp(random, '.left-counter span', 2222);
      };
    })(this));
  }

  padNum = function(number) {
    if (number < 10) {
      return '0' + number;
    }
    return number;
  };

  Fighters.prototype.countUp = function(points, selector, duration) {
    $({
      countNumber: $(selector).text()
    }).animate({
      countNumber: points
    }, {
      duration: duration,
      easing: 'linear',
      step: function() {
        $(selector).text(padNum(parseInt(this.countNumber)));
      },
      complete: function() {
        $(selector).text(points);
      }
    });
  };

  return Fighters;

})();
new window.Fighters();

1 个答案:

答案 0 :(得分:1)

点击功能每次都在运行,但对随机引用相同。在第一次执行脚本时对Random进行一次计算,然后在闭包中使用Random,而不是重新计算。 (如果你需要的话,你可以阅读大量关于封闭的文章 - 这里有一篇 - http://javascriptissexy.com/understand-javascript-closures-with-ease/

将随机内容置于闭包内,以确保在每次点击时对其进行评估,如下所示:

$('.punch1').on('click', (function(_this) {
      return function(e) {
          random = Math.ceil(Math.random() * 301232);
        return _this.countUp(random, '.right-counter span', 2222);
      };
    })(this));

http://jsfiddle.net/y6gwyv0x/1/

或随机创建一个返回其值

的函数
random = function(){return Math.ceil(Math.random() * 301232);};
$('.punch1').on('click', (function(_this) {
  return function(e) {

    return _this.countUp(random(), '.right-counter span', 2222);
  };
})(this));

random仍然是指闭包之外的那个,但因为它是一个函数,它将在每次单击时运行,返回一个新数字 http://jsfiddle.net/y6gwyv0x/3/