0

I have been wracking my brains as to how to achieve this. I have a containing element, which has two separate a tags within it that I want to addClass() to (i.e. when I hover over one a tag, it adds the class to that one, and the other a tag within that containing element). I kind of had it by using the below code:

<li class="element">
<header>
   <h1>Heading</h1>
</header>
   <a href="">
      <img src="image" alt=" dummy" />
   </a>
   <div>
      <h2><a href="">Heading 2</a></h2>
      <p>Paragraph</p>
   </div>
</li>

$('.element').hover(
 function() {
  $(this).children().addClass('hover');
},
 function() {
  $(this).children().removeClass('hover');
}
);

However I only want the hover triggered when on the 'a' itself, not on the entire element. Unfortunately, when I use this method:

$('.element a').hover(
 function() {
  $(this).addClass('hover');
},
 function() {
  $(this).removeClass('hover');
}
);

It only adds the class to the first 'a' tag.

Any advice would be greatly appreciated.

4

2 回答 2

0

您需要将 addClass 应用于每个元素......试试这个:

$('.element a').each(function() {
    $(this).hover(function() {
        $(".element a").each(function() {
            $(this).addClass('hover');
        });
    }, function() {
        $(".element a").each(function() {
            $(this).removeClass('hover');
        });

    });
});

http://jsfiddle.net/manseuk/GqP4Z/

于 2011-11-08T10:27:49.910 回答
0
$('.element a').hover(
 function() {
  $(this).add($(this).siblings()).addClass('hover');
},
 function() {
  $(this).add($(this).siblings()).removeClass('hover');
}
);

$(this) 仅包含被悬停的实际对象。我 .add() 将该对象的兄弟姐妹添加到该集合中,如果您愿意,可以使用 $(this).siblings('a') 或类似方法对其进行过滤。

于 2011-11-08T10:19:56.507 回答