javascript 单击时更改行的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17843478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:49:48  来源:igfitidea点击:

Changing the color of a row on click

javascript

提问by John Smith

Using pure javascript only:

仅使用纯 javascript:

How can I click on a specified table row, and change the background color of the selected row (for this example, lets use the color red).

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

Then, if the same row that was previously selected is clicked on again, change its background color back to default (white).

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

Here is my HTML:

这是我的 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>

回答by Unknown

$(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

jsFiddle 示例

回答by Adam MacDonald

something like this on your tr's would work ..

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

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

EDIT: didn't read your question properly ..

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

this would work:

这会起作用:

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

and on your tr:

并在您的 tr 上:

<tr onclick="changeColor(this)">

回答by Rick Klaassen

use jQuery and see example on http://jsfiddle.net/X2pJN/

使用 jQuery 并查看http://jsfiddle.net/X2pJN/ 上的示例

$('table tr').each(function(a,b){
    $(b).click(function(){
         $('table tr').css('background','#ffffff');
         $(this).css('background','#ff0000');   
    });
});