使用 jQuery 更改单击的表格行的颜色 [英] Changing the color of a clicked table row using jQuery

查看:27
本文介绍了使用 jQuery 更改单击的表格行的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要你的帮助

我如何使用 jQuery,

How can I, using jQuery,

更改表中选定行的背景颜色(对于本示例,让我们使用 css 类突出显示"

Change the background color of the selected row in my table (for this example, let's use the the css class "highlighted"

如果再次点击同一行,将其改回默认颜色(白色)选择css类nonhighlighted"

and if the same row is clicked on again, change it back to its default color (white) select the css class "nonhighlighted"

<!DOCTYPE html>

<html>

<head>

<style type="text/css">

.highlighted {
    background: red;
}
.nonhighlighted {
    background: white;
}
</style>

</head>

<body>

<table id="data" border="1" cellspacing="1" width="500" id="table1">
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
</table>

</body>

</html>

推荐答案

.highlight { background-color: red; }

如果你想要多选

$("#data tr").click(function() {
    $(this).toggleClass("highlight");
});

如果您只想一次选择表格中的 1 行

If you want only 1 row in the table to be selected at a time

$("#data tr").click(function() {
    var selected = $(this).hasClass("highlight");
    $("#data tr").removeClass("highlight");
    if(!selected)
            $(this).addClass("highlight");
});

另请注意,您的 TABLE 标签有 2 个 ID 属性,您不能这样做.

Also note your TABLE tag has 2 ID attributes, you can't do that.

这篇关于使用 jQuery 更改单击的表格行的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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