Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - jQuery - OnClick, change background color for table cells always when clicked

For example: You have a table, and it has 4 tds and 2 trs. Table's background color is white. If i click to A td, A td should be red, than if i click to B, B td should be red and A td should be red too. If i click to C than, C should be red and B and A should be red too.

I have something like this. But it isnt good, because when i click again i want to change color back to white.

http://jsfiddle.net/k8UgT/193/

The code i use

<table>
    <tr>
        <td onclick="function()">AAA</td>
        <td onclick="function()">BBB</td>
        <td onclick="function()">CCC</td>
    </tr>
        <tr>
        <td onclick="function()">DDD</td>
        <td onclick="function()">EEE</td>
        <td onclick="function()">FFF</td>
    </tr>
</table>

JS:

$( function() {
  $('td').click( function() {
    $(this).css('background', '#aaa')
  } );
} );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Welcome to SO.

First of all you don't need to onclick attribute on the td's. Second of all I would suggest using a CSS class instead of setting the background color.

CSS

.red-cell {
   background: #F00; /* Or some other color */
}

JS

$( function() {
  $('td').click( function() {
    $(this).toggleClass("red-cell");
  } );
} );

Read more about toggleClass here. Updated fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...