简体   繁体   中英

Changing background color onclick

I dont know if it is possible to do but i this is my code.

function start(blauw){  
    document.getElementById(blauw).style.background="white";
}

<table>
    <tr>
        <td id= niks></td>
        <td id= niks></td>
        <td id= blauw onclick="start(id)">1</td>
        <td id= blauw onclick="start(id)">2</td>
        <td id= blauw>3</td>
        <td id= blauw>4</td>
        <td id= blauw>5</td>
        <td id= blauw>6</td>
        <td id= blauw>7</td>
        <td id= blauw>8</td>
        <td id= niks></td>
        <td id= niks></td>
    </tr>
</table>

i want to achieve that if i click on it the background will turn into white so people now what they are booking. but do i have to give everything an own ID? because right now if i click on "2" only "1" turns white and "2" won't turn white.

(excuse me for my bad english)

Instead of passing attributes just pass the element itselfe:

  function start(element) { element.style.background = "green"; } 
  <table> <tr> <td class=niks></td> <td class=niks></td> <td class=blauw onclick="start(this)">1</td> <td class=blauw onclick="start(this)">2</td> <td class=blauw>3</td> <td class=blauw>4</td> <td class=blauw>5</td> <td class=blauw>6</td> <td class=blauw>7</td> <td class=blauw>8</td> <td class=niks></td> <td class=niks></td> </tr> </table> 

And as mentioned in the comments - ID`s had to be unique!!

EDIT:

Altered function to switch the background color.

    function start(element) {
        var backgroundColor = element.style.background;
        if (backgroundColor === "green") {
            element.style.background = "red";
        } else {
            element.style.background = "green";
        }
    }

So this is a very simple demo

See FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM