单击时更改行的颜色

时间:2013-07-24 19:44:03

标签: javascript

仅使用纯JavaScript:

如何单击指定的表格行,并更改所选行的背景颜色(对于此示例,我们使用红色)。

然后,如果再次单击先前选择的同一行,请将其背景颜色更改回默认值(白色)。

这是我的HTML:

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Language" content="en-ca">

</head>

<body>

<table border="1" cellspacing="1" width="100%" id="table1">
    <tr>
        <th>Column1</th>
        <th>Column2</th>
        <th>Column3</th>
        <th>Column4</th>
        <th>Column5</th>
    </tr>
    <tr>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
    </tr>
    <tr>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
        <td>data</td>
    </tr>
</table>

</body>

</html>

3 个答案:

答案 0 :(得分:8)

$(document).ready(function () {
    $('tr').click(function () {
        //Check to see if background color is set or if it's set to white.
        if(this.style.background == "" || this.style.background =="white") {
            $(this).css('background', 'red');
        }
        else {
            $(this).css('background', 'white');
        }
    });
});

jsFiddle Example

答案 1 :(得分:3)

在你的tr上这样的东西会起作用..

<tr onclick="this.style.backgroundColor='red'">

编辑:没有正确阅读你的问题..

这样可行:

<script>
    function changeColor(o){
        o.style.backgroundColor=(o.style.backgroundColor=='red')?('transparent'):('red');
    }
</script>

和你的tr:

<tr onclick="changeColor(this)">

答案 2 :(得分:0)

使用jQuery并查看http://jsfiddle.net/X2pJN/

上的示例
$('table tr').each(function(a,b){
    $(b).click(function(){
         $('table tr').css('background','#ffffff');
         $(this).css('background','#ff0000');   
    });
});
相关问题