2014-08-28 28 views
-5

所以我的計數器只是第一次工作。 通過再次點擊按鈕,我需要繼續計數,但該功能在第一次運行後不起作用,任何人都知道該怎麼做?JS數字計數器只能工作一次

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

我的JS,如果你不想的jsfiddle看到:

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() * 3); 
    $('.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(); 
+2

問題:「爲什麼不是這段代碼工作?應該修改以符合SO的指導方針http://stackoverflow.com/help/on-topic(第一類) – Blubberguy22 2014-08-28 19:22:54

+0

我認爲這符合指導方針「必須包括所需行爲」檢查,「特定問題或錯誤」檢查「,以及在問題本身中重現它的最短代碼」檢查。 – Quince 2014-08-28 19:51:48

回答

1

單擊功能運行每次但具有相同的參考隨機的。隨機在您的腳本的第一次執行時被評估一次,然後在您的關閉中使用,而不是重新評估。 (字面噸關於關閉該文章你可以,如果你需要閱讀起來 - 這裏是一個 - http://javascriptissexy.com/understand-javascript-closures-with-ease/

帶上隨機的閉包,以確保它在評估每按一下,像這樣:

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

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

或進行隨機返回它的值

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

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

隨機還指功能封閉外的一個,但因爲它是一個函數,它將在每次點擊時運行,返回一個新的數字 http://jsfiddle.net/y6gwyv0x/3/

+0

我真的很感謝你這個太完整的答案! – 2014-08-28 20:00:17