Javascript 所有 table 数据

Javascript on all table data

我正在使用以下 Javscript 在鼠标悬停时更改 table 数据元素 ID,以便我可以在鼠标操作上应用不同的 CSS。它工作正常,但只在我的 table 的第一行。有谁知道我如何修改脚本,以便它应用于我的 table 中的每一行?

$('#tdcns').mouseover(function(){
$(this).attr('id', 'hovertdcns');
});
$('#tdcns').mouseout(function(){
$(this).attr('id', 'tdcns');
});

非常感谢任何指导!

问题是多个对象的 ID 相同。避免那样! 如果您使用 类 作为 JQuery 选择,它将按预期工作。

我的示例有效。您还应该考虑将样式更改为基于 类。

$('.test').mouseover(function(){
$(this).attr('id', 'testhover');
});
$('.test').mouseout(function(){
$(this).attr('id', 'test');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Hallo</div>
<div class="test">Welt</div>
<div class="test">Ein</div>
<div class="test">Element</div>

如我的评论所述,您的 ID 应该是唯一的。然而,这在没有 JS 的情况下更好地实现,而是使用 CSS.

tr {
  font-size: 2em;
}
tr:hover {
  background: orange;
}
<table>
  <tr><td>foo
  <tr><td>bar
  <tr><td>baz
  <tr><td>yaz
</table>