Seven circles but only one is changing colour, why?

前端 未结 8 1252
梦谈多话
梦谈多话 2021-01-26 09:29

I am new to javascript and I have an assignment to create seven circles which should change colour on a mouse click. The first circle is changing colour but the other six just r

8条回答
  •  梦毁少年i
    2021-01-26 09:56

    You have multiple element with same id. Instead of id use class and add event listener to it

    var circle = document.getElementsByClassName("circle");
    let colors = ['orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
    
    [...circle].forEach(function(item, index) {
      item.addEventListener('click', function(e) {
        item.style.fill = colors[index]
      })
    })

    Rainbow Colours

提交回复
热议问题