Seven circles but only one is changing colour, why?

前端 未结 8 1253
梦谈多话
梦谈多话 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:36

    Use querySelectorAll('circle') to query all circles by their element name.

    Also do not use the same id on all circles, element ids must be unique.

    You can then use a forEach to iterate on your circles and attach your click handler with circle.addEventListener('click', handler).

    Using this technique, you don't need ids or classes to refer to your circles, and you can also remove your onclick handler on each circle in your HTML:

    
    

    Here is an example:

    const circles = document.querySelectorAll('circle');
    
    const colors = ['orange', 'yellow', 'green', 'blue', 'indigo','violet'];
    
    circles.forEach(circle => {
      circle.addEventListener('click', () => {
        color = colors.shift();
        colors.push(color);
        circle.style.fill = color;
      });
    });
     
      
      
      
      
      
      
      
    

提交回复
热议问题