Seven circles but only one is changing colour, why?

前端 未结 8 1248
梦谈多话
梦谈多话 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条回答
  •  鱼传尺愫
    2021-01-26 09:32

    Elements in HTML must have a unique id attribute, otherwise, your HTML is considered invalid.

    Instead, you should use a class, this way you can iterate through your selected elements (here I have used .forEach), and apply the click handler to each.

    Note: Now that you're using a class, you need to use getElementsByClassName() which will give you a HTMLCollection of matching elements.

    See working example below:

    const circles = [...document.getElementsByClassName("circle1")], // use spread syntax to convert collection to array
    colors = ['orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
    
    circles.forEach(circle => {
      circle.onclick = function() {
        color = colors.shift();
        colors.push(color);
        circle.style.fill = color;
      }
    });

    Rainbow Colours

提交回复
热议问题