jQuery - OnClick,始终在单击时更改表单元格的背景颜色 [英] jQuery - OnClick, change background color for table cells always when clicked

查看:127
本文介绍了jQuery - OnClick,始终在单击时更改表单元格的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:
您有一个表,它有4 tds和2 trs。表的背景颜色是白色。如果我点击A td,A td应该是红色的,如果我点击B,B td应该是红色的,A td也应该是红色的。如果我点击C比,C应该是红色的,B和A也应该是红色的。

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/

我使用的代码

<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')
  } );
} );


推荐答案

欢迎来到SO。

首先,你不需要在td的 onclick 属性。其次,我建议使用CSS类,而不是设置背景颜色。

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");
  } );
} );

详细了解toggleClass 此处
已更新小提琴

Read more about toggleClass here. Updated fiddle

这篇关于jQuery - OnClick,始终在单击时更改表单元格的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆