2

我想在前 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次。处理这个问题的最佳方法是什么?

4

3 回答 3

5

看一下lt选择器:

$('tr td:lt(24)')

http://api.jquery.com/lt-selector/

于 2013-01-28T23:41:31.917 回答
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

于 2013-01-28T23:40:24.587 回答
0

在封闭表上使用事件委托会更好地执行:

$('#mytable').on('mouseover', 'td:lt(24)', function() {
    var n = $(this).index();
    $('rect').eq(n).css('fill', 'black');
});

这比将相同的函数绑定到每个匹配元素更有效。

于 2013-01-28T23:53:08.690 回答