2016-11-17 77 views
0

我試圖將相同的功能應用於三個不同的ID。我創建了一個小提琴來說明這個:https://jsfiddle.net/jnoweb/xrpsshcp/如何使用相同功能定位三個ID?

var game = {score:0}, 
scoreDisplay = document.getElementById("score1"); 

function add20() { 
    TweenLite.to(game, 1, { 
     score:"+=20", 
     roundProps:"score", 
     onUpdate:updateHandler, 
     ease:Linear.easeNone 
    }); 
} 

function updateHandler() { 
    scoreDisplay.innerHTML = game.score; 
} 

add20(); 

所以我想以同樣的方式作爲紅色數字動畫的黑色數字。有任何想法嗎?

謝謝!

回答

1

步驟1:請元素的Array,將其存儲在scoreDisplay喜歡你的第一個元素一樣。

scoreDisplay = [ 
    document.getElementById("score1"), 
    document.getElementById("score2"), 
    document.getElementById("score3") 
]; 

步驟2:執行您的更新函數的每個元素,通過使用Array.prototype.forEach

function updateHandler() { 
    scoreDisplay.forEach(function(display) { 
    display.innerHTML = game.score; 
    }); 
} 

在您的提琴:https://jsfiddle.net/ku72qy7e/

相關問題