jquery td 的悬停范围

标签 jquery css jquery-selectors

我是新来的,找不到任何与我想要的类似的答案;我已经取得了进步,但无法更进一步。下面是我的截图,当我将鼠标悬停在倒数第二个到倒数第二个 TR 之间时,它会改变颜色。 (第一个 TR 是标题,最后一个 TR 是页脚)。在可悬停范围之间,如何选择仅包括第二个 TD 和倒数第二个 TD。

$('table#tblSchoolList tr:gt(0)').hover(function(){
    ////and not the last child (.next length = 0 means last)
    if ( $(this).next().length != 0 ){
        $(this).css("background", "red");  
    }
}, function(){
    $(this).css("background", "");
})

简而言之,表格悬停排除第一个和最后一个 TR 和 TD。

TIA。

最佳答案

您可以使用.find()使用以下选择器排除每个 tr 的第一个和最后一个 td:

$('table#tblSchoolList tr:gt(0)').hover(function() {
    if ($(this).next().length != 0) {
        $(this).find('td:not(:first-child, :last-child)').css("background", "red");  
    }
}, function() {
    $(this).find('td:not(:first-child, :last-child)').css("background", "");
});

如果鼠标位于第一个和最后一个 td 上,该函数仍会触发,但它们不会着色。

jsFiddle demo

您还可以将选择器与 tr 一起使用,从而无需使用 if 语句:

$('table#tblSchoolList tr:not(:first-child, :last-child)').hover(function() {
    $(this).find('td:not(:first-child, :last-child)').css("background", "red");
}, function() {
    $(this).find('td:not(:first-child, :last-child)').css("background", "");
});
<小时/>

作为一个小好处,我注意到我能够将所有 jQuery 代码转换为一个 CSS 规则(仅适用于现代浏览器):

table#tblSchoolList tr ~ tr:not(:last-child):hover td ~ td:not(:last-child) {
    background: red;
}

当然,如果您想与旧版浏览器兼容或者无法弄清楚上述 CSS 的含义,您可以随时保留 jQuery 解决方案:)

jsFiddle demo

关于jquery td 的悬停范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6893608/

相关文章:

javascript - 为什么我不能使用 jquery 延迟 addClass 和 removeClass?

jquery ajax post 被调用时停止

javascript - 仅在 IE 中按钮位置不正确

javascript - 基本的 jQuery 选择器问题

javascript - 选择以空格分隔的单词的元素

javascript - jQuery - 代码检查是否有任何字段不为空,然后将所有字段设为必填

javascript - <div> 的大小应始终保持不变

css - 使用固定页脚图像重复动态长度的背景图像

javascript - 使用 jquery,当我单击链接时,如何引用其上方的选择下拉列表?

javascript - 退出全屏不起作用?