我想在前24个孩子上添加一个悬停,在另一个元素的24个单独元素上添加填充。
像这样:
$('tr td:nth-child(1)').mouseover(function(){
$('rect:nth-of-type(1)').css("fill", "black" );
});
$('tr td:nth-child(2)').mouseover(function(){
$('rect:nth-of-type(2)').css("fill", "black" );
});
$('tr td:nth-child(3)').mouseover(function(){
$('rect:nth-of-type(3)').css("fill", "black" );
});
但我不想重复自己24次。什么是解决这个问题的最好方法?
答案 0 :(得分:5)
答案 1 :(得分:1)
$('tr td:lt(24)').mouseenter(function(){
var index = $(this).index();
$('rect').eq( index ).css("fill","black");
});
如果您的元素数不超过24个,则不需要:lt()
选择器
您也可以使用JS方法.slice()
,如:
$('tr td').slice(0,24)
您还可以使用.eq()
(或:eq()-selector
)定位所需元素,然后使用.prevAll()
$('tr td:eq(24)').prevAll()
使用#ID
答案 2 :(得分:0)
这将使用封闭表上的事件委派更好地执行:
$('#mytable').on('mouseover', 'td:lt(24)', function() {
var n = $(this).index();
$('rect').eq(n).css('fill', 'black');
});
这比将相同的函数绑定到每个匹配元素更有效。