【问题标题】:jquery hover range of tdtd的jquery悬停范围
【发布时间】:2011-08-01 12:35:49
【问题描述】:

我是新来的,找不到任何与我想要的类似的答案;我已经取得了进步,不能再进一步了。下面是我的截图,当我悬停在最后一个 TR 的第 2 到第 2 之间时,它会改变颜色。 (第一个 TR 是标题,最后一个 TR 是页脚)。在可悬停范围之间,我如何选择它只包括 2nd TD 和 2nd last 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。

【问题讨论】:

  • 您的意思是当您悬停该行时,只更改每行的第二个和倒数第二个单元格的颜色?
  • 上面的代码对我有用,正如您描述的要求(突出显示第一个和最后一个之间的所有 trs) - 请参阅 jsfiddle.net/cK8Q5/1
  • 是的 BoltClock。 Ken Redler 刚刚改进了 tr 范围选择,但没有解决我的问题。单元格的数量是动态的,概念与tr相同,只是不是第一个和最后一个单元格。

标签: jquery css jquery-selectors


【解决方案1】:

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

$('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", "");
});

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

jsFiddle demo

您还可以将选择器与 trs 一起使用,从而无需 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

【讨论】:

  • 感谢您的信息。很高兴知道 CSS 规则也是这样工作的。
【解决方案2】:

您可以尝试使用slice,如下所示:

$('table#tblSchoolList tr').slice(1,-1).hover( function(){
  $(this).css("background", "red");  
}, function(){
  $(this).css("background", "");
});

使用负数指定距离列表末尾的偏移量。所以:

slice(
  1, // omit first row
  -1 // omit last row
)

或者更简单地说:

$('table#tblSchoolList tr').slice(1,-1).hover( function(){
  $(this).toggleClass('highlight');
});

(假设您有一个 highlight 类来处理颜色行为)。


编辑: 更新以确保第一列和最后一列以及行不突出显示(感谢@boltclock):
$('#foo tr').slice(1,-1).hover( function(){
  $(this).find('td').slice(1,-1).toggleClass('highlight');
});

这是一个非常简单的例子:http://jsfiddle.net/redler/Mgd8f/

【讨论】:

  • 那么...tds 呢?现在你所做的就是重构 OP 已经拥有的东西。
  • 感谢 Ken,您的建议改进了我现有的选择,但没有解决我想要的问题。即在 tr.slice() 之间,我还想要“td.slice()”,类似于“$('table#tblSchoolList tr').slice(1,-1).('td').slice(1, -1)" 不可能吗?
  • 我使用了选择器,但我承认切片要简单得多。
猜你喜欢
  • 1970-01-01
  • 2013-04-13
  • 2011-01-18
  • 2016-12-28
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-27
相关资源
最近更新 更多