开发者

JQuery How to select all anchors within current list item?

开发者 https://www.devze.com 2023-01-12 11:39 出处:网络
I wish to, using JQuery, show and hide some anchor tags as I hover over a list item. How do you loop through the current anchors within a list item using $(this) ?

I wish to, using JQuery, show and hide some anchor tags as I hover over a list item.

How do you loop through the current anchors within a list item using $(this) ?

Here's what I have so far:

$(document).ready(function() {
    $('.currentlist > li').mouseover(function(event){
        // loop through each anchor tag within this list using $(this)
        // and add the .a开发者_运维问答ctive 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>


Try this:

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

Where $(this) refers to hovered li and $('a', $(this)) context selector is used to find all links inside them and add/remove classes.


You can use .hover() to shorten the events, .find() to get the anchors and .addClass() and .removeClass() to toggle .active on and off, like this:

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

You'll want to use .hover() here because mouseover and mouseout will fire when entering and exiting children, where mouseenter and mouseleave (which .hover() uses) won't).

Also your CSS needs a fix, this:

a .active
{
  display: block;
}

Shouldn't have a space, it should be like this:

a.active
{
  display: block;
}

Also, it should be moved to the end so it overrides the .edit-icon and .delete-icon definitions.

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


Something like

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

should do it for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号