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

Javascript JS数字计数器只工作一次,javascript,jquery,Javascript,Jquery,所以我的计数器第一次工作。 通过再次点击按钮,我需要继续计数,但第一次运行后该功能不起作用,有人知道怎么做吗 我的朋友: 如果您不想在JSFIDLE中看到My js: window.Fighters = (function() { var padNum; function Fighters(options) { var random; this.greenFighter = $('.green-fighter'); this.blueFighter = $('.

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

我的朋友:

如果您不想在JSFIDLE中看到My 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();

click函数每次都在运行,但对random的引用相同。Random在脚本第一次执行时计算一次,然后在闭包中使用,而不是重新计算。如果需要,你可以阅读大量与闭包相关的文章-这里有一篇-

在闭包中放入随机项,以确保每次单击时都对其进行评估,如下所示:

$('.punch1').on('click', (function(_this) {
      return function(e) {
          random = Math.ceil(Math.random() * 301232);
        return _this.countUp(random, '.right-counter span', 2222);
      };
    })(this));
或者随机生成一个返回其值的函数

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仍然是指闭包之外的函数,但因为它是一个函数,所以每次单击时都会运行它,返回一个新的数字

问为什么此代码不起作用的问题?应该修改以符合第一类的指导原则。我会说,这符合指导原则必须包括所需的行为检查、特定问题或错误检查,以及在问题本身检查中复制它所需的最短代码。我非常感谢您提供了这个太完整的答案!!!!