单击td时,更改bgcolor

When td is clicked change bgcolor?

本文关键字:更改 bgcolor td 单击      更新时间:2024-03-21

我在获取html表以更改单个td`时遇到一些问题

$(document).ready(function(){
    $("#table1 > td").click(function(){
        $(this).toggleClass("active");
    });
});
table td.active {
    background: #006633;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table width="100%" border="0" id="table1">
                    <tr>
                    <td colspan="6" height="20px" bgcolor="#CCCCCC"><strong>CULTURE</strong></td>
                    </tr>
               
                    <tr>
                    <td width="5%"><p align="center">1</p></td>
                    <td width="40%">Is the CDP obvious - You Said / We Did Boards; Feedback Stations; Posters?</td>
                    <td width="5%" height="20px"><p align="center">1</p></font></td>
                    <td width="5%" height="20px"><p align="center">2</p></font></td>
                    <td width="5%" height="20px"><p align="center">3</p></font></td>
                    <td width="5%" height="20px"><p align="center">4</p></font></td>
                    </tr>
    </table>

单击when the td`。由于某种原因,当它被点击时,它什么也不做。有人知道为什么会这样吗?

$("#table1 > td")$("#table1 td"),但这将增加您选择的匹配项。因此,我建议添加一个唯一的属性(我鼓励data-*)。

$(document).ready(function(){
    /*
    $("#table1 td").click(function(){
        $(this).toggleClass("active");
    });
    */
    // Better
    $("#table1 td[data-toggle]").click(function(){
        $(this).toggleClass("active");
    });
});
table td.active {
    background: #006633;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table width="100%" border="0" id="table1">
                    <tr>
                    <td colspan="6" height="20px" bgcolor="#CCCCCC"><strong>CULTURE</strong></td>
                    </tr>
               
                    <tr>
                    <td width="5%"><p align="center">1</p></td>
                    <td data-toggle width="40%">Is the CDP obvious - You Said / We Did Boards; Feedback Stations; Posters?</td>
                    <td data-toggle width="5%" height="20px"><p align="center">1</p></font></td>
                    <td data-toggle width="5%" height="20px"><p align="center">2</p></font></td>
                    <td data-toggle width="5%" height="20px"><p align="center">3</p></font></td>
                    <td data-toggle width="5%" height="20px"><p align="center">4</p></font></td>
                    </tr>
    </table>

$("#table1>td")表示td是表中的第一个子元素。这不是真的,因为这就是你的tr。只需将其更改为$("#table1TD"),即可完成(删除'>')。

$('#table1 > td')更改为$('#table1 td'),因为td不是表1的第一个子级。

 $(document).ready(function(){
        $("#table1 td").click(function(){
            $(this).toggleClass("active");
        });
    });

在这里查看jsFiddle中的演示:https://jsfiddle.net/jagrati16/7ychbmht/