Seven circles but only one is changing colour, why?

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

    In the onclick function pass the element itself using this keyword. It works in this case but remember it is wrong to give same id to more than 1 element. It should be unique.

    var circle = document.getElementById("circle1");
    
    
    colors = ['orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
    function a(e)
    
    {
      color = colors.shift();
      colors.push(color);
    
      e.style.fill = color;
    }
    <html>
    <body>
      <h2> Rainbow Colours</h2>
      <svg height="1000" width="500"> 
        <circle  id="circle1" onclick="a(this)"  cx="50" cy="50" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" onclick="a(this)"  cx="50" cy="150" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" onclick="a(this)"  cx="50" cy="250" r="40"  
    style="fill:red;"/>
        <circle  id ="circle1" onclick="a(this)"  cx="50" cy="350" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" onclick="a(this)"  cx="50" cy="450" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" onclick="a(this)"  cx="50" cy="550" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" onclick="a(this)"  cx="50" cy="650" r="40" 
    style="fill:red;"/>
        </svg>
    </body>
    
    </html>

    0 讨论(0)
  • 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]
      })
    })
    <h2> Rainbow Colours</h2>
    <svg height="1000" width="500"> 
        <circle  id="circle1" class ="circle" cx="50" cy="50" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" class ="circle"cx="50" cy="150" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" class ="circle"  cx="50" cy="250" r="40"  
    style="fill:red;"/>
        <circle  id ="circle1" class ="circle"  cx="50" cy="350" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" class ="circle"  cx="50" cy="450" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" class ="circle"  cx="50" cy="550" r="40" 
    style="fill:red;"/>
        <circle  id ="circle1" class ="circle"  cx="50" cy="650" r="40" 
    style="fill:red;"/>
    </svg>

    0 讨论(0)
提交回复
热议问题