我是新来的,找不到任何与我想要的类似的答案;我已经取得了进步,但无法更进一步。下面是我的截图,当我将鼠标悬停在倒数第二个到倒数第二个 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
上,该函数仍会触发,但它们不会着色。
您还可以将选择器与 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 解决方案:)
关于jquery td 的悬停范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6893608/