我如何用相同的功能瞄准三个id

How can I target three IDs with the same function?

本文关键字:id 三个 何用相 功能      更新时间:2023-09-26

我试图将相同的函数应用于三个不同的id。我创建了一个小提琴来说明这一点:https://jsfiddle.net/jnoweb/xrpsshcp/

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(); 

所以我试着用和红色数字一样的方式来动画黑色数字。什么好主意吗?

谢谢!

第一步:创建元素的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/