jQuery:添加类<tr>鼠标悬停,以样式<td>

jQuery: Add class to <tr> on mouseover in order to style <td>

本文关键字:td 样式 悬停 tr 添加 jQuery 鼠标      更新时间:2023-09-26

我试图在鼠标悬停(突出显示)时添加一个类到<tr>,其中我将对子<td> 's进行样式化。只是在<tr>上添加所需的效果(背景色)是不行的,因为内部<td> 's的bg属性。

我已经确保jquery正在运行,我使用1.9分钟。

这是我目前为止写的:

$('table tr').mouseover(function(){
    $(this).addClass('highlight');
}).mouseout(function(){
    $(this).removeClass('highlight');
});

我在CSS中有相应的.hightlight类设置,如.highlight td {},以样式<td> 's,当高亮类添加到<tr>时。

无论如何,我都想不出我在这里做错了什么。我已经测试了<td>的样式是正确的手动添加class="highlight"<tr>,这是有效的。

任何帮助都是感激的。谢谢。

我想到的唯一事实是将您的代码放在$(document).ready()处理程序中:

$(function() {
    $("table tr").hover(function() {
        $(this).addClass("highlight");
    }, function() {
        $(this).removeClass("highlight");
    });
});

…或者使用更方便的.hover()方法。

演示:

http://jsfiddle.net/B2Rnz/

您只能定义一个.highlight声明并将其应用于<td>:

 $(function() {
     $('table tr').on('mouseover', 'td', function(){
           $(this).addClass('highlight');
       }).on('mouseout', 'td', function(){
           $(this).removeClass('highlight');
       });
 });

如果没有更多的逻辑涉及,你也可以使用纯CSS:

tr:hover td {
    background: #333;
}