[英]jQuery: Add class to <tr> on mouseover in order to style <td>
I'm trying to append a class to a <tr>
when mousing over (highlight), in which I will be styling the child <td>
's. 当我将鼠标移动(突出显示)时,我试图将一个类附加到
<tr>
,其中我将为孩子设置样式<td>
。 Just adding the desired effect (background color) on the <tr>
won't do, because of the bg properties of the internal <td>
's. 由于内部
<td>
的bg属性,在<tr>
上添加所需的效果(背景颜色)是行不通的。
I've made sure jquery is running, and I'm using 1.9 min. 我已经确定jquery正在运行,而我正在使用1.9分钟。
This is what I have so far: 这是我到目前为止:
$('table tr').mouseover(function(){
$(this).addClass('highlight');
}).mouseout(function(){
$(this).removeClass('highlight');
});
I have the corresponding .hightlight
class setup in CSS as in .highlight td {}
to style the <td>
's when the highlight class is added to the <tr>
. 我在CSS中有相应的
.hightlight
类设置,如.highlight td {}
,当高亮类添加到<tr>
时设置<td>
的样式。
I can't, for the life of me, figure out what I'm doing wrong here. 我不能,为了我的生活,弄清楚我在这里做错了什么。 I've tested that the
<td>
's are styled correctly by manually adding class="highlight"
to the <tr>
, and that works. 我通过手动将
class="highlight"
添加到<tr>
来测试<td>
的样式是否正确,这是有效的。
Any help is appreciated. 任何帮助表示赞赏。 Thanks guys.
多谢你们。
The only fact that comes to my mind is placing your code in the $(document).ready()
handler: 我想到的唯一事实是将代码放在
$(document).ready()
处理程序中:
$(function() {
$("table tr").hover(function() {
$(this).addClass("highlight");
}, function() {
$(this).removeClass("highlight");
});
});
... and maybe using more handy .hover()
method instead. ...而且可能使用更方便的
.hover()
方法。
DEMO: http://jsfiddle.net/B2Rnz/ 演示: http : //jsfiddle.net/B2Rnz/
If there is no more logic involved you can also use plain CSS: 如果不再涉及逻辑,您也可以使用纯CSS:
tr:hover td {
background: #333;
}
You could define only one .highlight
declaration and apply it to the <td>
: 您只能定义一个
.highlight
声明并将其应用于<td>
:
$(function() {
$('table tr').on('mouseover', 'td', function(){
$(this).addClass('highlight');
}).on('mouseout', 'td', function(){
$(this).removeClass('highlight');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.