-1

彼は開発者、

このコードをより適切に記述する方法について、あなたの意見を知りたいです。

ボタン star3 をクリックすると、黄色の星に変わります。その下の星も黄色です。star3 の上の星は灰色です。

それは私が得たものであり、必要なものですが、コードをより効率的にする方法を知りたい..

var star = document.getElementById("star-0");
 var star1 = document.getElementById("star-1");
 var star2 = document.getElementById("star-2");
 var star3 = document.getElementById("star-3");
 var star4 = document.getElementById("star-4");
 var img = 'url(img/star.png)';
 var img2 = 'url(img/star2.png)';


star4.addEventListener('click', function(){
   star.style.backgroundImage = img2;
   star1.style.backgroundImage = img2;
   star2.style.backgroundImage = img2;
   star3.style.backgroundImage = img2;
   star4.style.backgroundImage = img2;
});

star3.addEventListener('click', function(){
   star.style.backgroundImage = img2;
   star1.style.backgroundImage = img2;
   star2.style.backgroundImage = img2;
   star3.style.backgroundImage = img2;
   star4.style.backgroundImage = img;
});

star2.addEventListener('click', function(){
   star.style.backgroundImage = img2;
   star1.style.backgroundImage = img2;
   star2.style.backgroundImage = img2;
   star3.style.backgroundImage = img;
   star4.style.backgroundImage = img;
});

star1.addEventListener('click', function(){
   star.style.backgroundImage = img2;
   star1.style.backgroundImage = img2;
   star2.style.backgroundImage = img;
   star3.style.backgroundImage = img;
   star4.style.backgroundImage = img;
});

star.addEventListener('click', function(){
   star.style.backgroundImage = img2;
   star1.style.backgroundImage = img;
   star2.style.backgroundImage = img;
   star3.style.backgroundImage = img;
   star4.style.backgroundImage = img;
});

4

3 に答える 3