jQuery - 在悬停时更改表格行颜色,让悬停事件生效

bet*_*oys 14 jquery

我想通过使用jQuery更改其颜色来突出显示表行.进行RTFM,广泛试验和研究,运气不佳.

HTML:

<table id="waypointsTable" border="1">
<tbody>
<tr>
<td>some text</td>
</tr> ...
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

$('#waypointsTable > tbody > tr > td').hover(function() {
    alert(1);
}, function() {
    alert(2);
});
Run Code Online (Sandbox Code Playgroud)

在这一点上,我只是试图让悬停功能解雇.应该悬停在tr还是td?在选择表格行和td时,我是否总是必须包含tbody参考?在每个tr或td上放一个课而不是上面的方法更好吗?

谢谢.

nic*_*las 32

看起来很好,如果你想触发每一行,你可以直接绑定到tr.

只是:

$('#waypointsTable tr').hover(function() {
    $(this).addClass('hover');
}, function() {
    $(this).removeClass('hover');
});
Run Code Online (Sandbox Code Playgroud)

(完整代码http://jsfiddle.net/nicholasstephan/8nbVG/)

应该管用...

特别是对于这种情况,使用css:hover伪选择器也可以完成这项工作.

#waypointsTable tr:hover {
    background-color:yellow;
}
Run Code Online (Sandbox Code Playgroud)


bpb*_*t77 6

<script type="text/javascript">

$("tr").not(':first').hover(
  function () {
    $(this).css("background","yellow");
  }, 
  function () {
    $(this).css("background","");
  }
);

</script>
Run Code Online (Sandbox Code Playgroud)

演示