JQuery如何选择当前列表项中的所有锚点?

问题描述:

我希望使用JQuery,当我将鼠标悬停在列表项上时,显示并隐藏一些锚标签。JQuery如何选择当前列表项中的所有锚点?

如何使用$(this)循环显示列表项目中的当前锚点?

这是我到目前为止有:

$(document).ready(function() { 
    $('.currentlist > li').mouseover(function(event){ 
     // loop through each anchor tag within this list using $(this) 
     // and add the .active class 
    }); 
    $('.currentlist > li').mouseout(function(event){ 
     // loop through each anchor tag within this list using $(this) 
     // and remove the .active class 
    }); 
}); 


a .active 
{ 
    display: block; 
} 

a.edit-icon 
{ 
    display: none; 
} 

a.delete-icon 
{ 
    display: none; 
} 

<ul class="currentlist"> 
    <li><a href="#" class="active">index</a><a href="#" class="edit-icon">edit</a><a href="#" class="delete-icon">delete</a></li> 
    <li><a href="#" class="active">profile</a><a href="#" class="edit-icon">edit</a><a href="#" class="delete-icon">delete</a></li> 
    <li><a href="#" class="active">contactus</a><a href="#" class="edit-icon">edit</a><a href="#" class="delete-icon">delete</a></li> 
    <li><a href="#" class="active">findus</a><a href="#" class="edit-icon">edit</a><a href="#" class="delete-icon">delete</a></li> 
</ul> 

试试这个:

$(document).ready(function() { 
    $('.currentlist > li').mouseover(function(event){ 
     $(this).find('a').addClass('active'); 
    }); 
    $('.currentlist > li').mouseout(function(event){ 
     $(this).find('a').removeClass('active'); 
    }); 
}); 

$(this)指徘徊li$('a', $(this))上下文选择用于查找在他们里面的所有链接,并添加/删除类。

+0

@Sarfaz - 谢谢 - 希望我的复制和粘贴没有任何问题,但是..它不工作。 – 2010-08-17 15:20:49

+0

@Nicholas Murray:我修改了代码;请:) – Sarfraz 2010-08-17 15:22:34

+0

@Sarfaz - 我必须做一些愚蠢的事这里是两个部分的实际代码:

测试 2010-08-17 15:41:34

喜欢的东西

$(event.currentTarget).find("a.active").removeClass("active") 

应该为你做它。

您可以使用.hover()缩短事件,.find()得到主持人和.addClass().removeClass()对切换.active和关闭,就像这样:

$(function() { 
    $('.currentlist > li').hover(function() { 
    $(this).find('a').addClass('active'); 
    }, function() { 
    $(this).find('a').removeClass('active'); 
    }); 
}); 

你要在这里使用.hover()因为mouseovermouseout将在进入和退出儿童时触发,其中mouseentermouseleave(其使用.hover())不会)。

而且你的CSS需要修复,这一点:

a .active 
{ 
    display: block; 
} 

应该不会有空间,就应该是这样的:

a.active 
{ 
    display: block; 
} 

而且,它应该被移动到年底使它会覆盖.edit-icon.delete-icon的定义。

Here's a working version with all of the above changes

+0

哇从来没有见过那个jsFiddle之前那个石头! – 2010-08-17 15:38:38

+0

@Nicholas - 你在这个答案修复后仍然有问题吗? – 2010-08-17 15:52:36

+0

现在不行。感谢您通过jsFiddle的综合答案。我认为JQuery的问题必须绘制这个星球上最快的枪支! – 2010-08-17 15:59:41