如何将类添加到链接悬停在jQuery中的下一个td?

时间:2011-08-11 11:39:32

标签: jquery hover addclass html-table

我有6个像这样:

<td><a href="#">link</a></td>
<td>Some text here</td>

<td><a href="#">link</a></td>
<td>Some other text here</td>

<td><a href="#">link</a></td>
<td>Some other other text here</td>

我希望将鼠标悬停在指向下一个td的链接上。例如。如果我将鼠标悬停在第二个td的链接上,则下一个td会有一个类,例如活动,就像这样

<td><a href="#">link</a></td>
<td>Some text here</td>

<td><a href="#">link</a></td> <!-- hoovering over this link -->
<td class="active">Some other text here</td> <!-- and this td will have class active-->

<td><a href="#">link</a></td>
<td>Some other other text here</td> 

怎么做?

3 个答案:

答案 0 :(得分:2)

$('a').hover(function(){
    $(this).parent().next().addClass('someclass');
}, function(){
    $(this).parent().next().removeClass('someclass');
});

答案 1 :(得分:1)

jQuery(function($){
    $("a").hover(function(){
       $(this).parent().next("td").addClass("active");
    });
});

以下是fiddle

答案 2 :(得分:1)

这不仅可以在悬停时添加类,还可以在将鼠标悬停在链接上时将其删除。当您在页面上有其他标签时,它也可以使用。不仅仅是td内的那些。

$(document).ready(function() {
    $("td > a").hover(function() {
       $(this).parent().next("td").toggleClass("active");
    });
});