I have a problem. Everytime I mouseover my list (doesn't matter which list item it is) the class .hover is added across the whole list. So is class .over. I realize I am adding those through jquery but how can have jquery only addclass to one list anchor only rather than all of them across the board.
$('.menuContainer li a').append('<span></span>');
$(".menuContainer li a").mouseover(
function() {
开发者_如何学JAVA $(this).addClass("over");
$('.menuContainer li a span').addClass('hover');
return false;
});
$(".menuContainer li a").mouseout(
function() {
$(this).removeClass("over");
$('.menuContainer li a span').removeClass('hover');
return false;
});
<div class="menuContainer">
<ul>
<li class="1">
<a href="#">list item<span></span></a>
</li>
<li class="2">
<a href="#">list item<span></span></a>
</li>
<li class="3">
<a href="#">list item<span></span></a>
</li>
</ul>
</div>
My goal is to have the class .hover with a background image that will be a pointer to emphasize what is currently being moused over.
Because you want to select the span of the current anchor, you should use the following notation $("span", this)
as the selector... looks like this:
$('.menuContainer li a').append('<span></span>');
$(".menuContainer li a").mouseover(
function() {
$(this).addClass("over");
$("span", this).addClass('hover');
return false;
});
$(".menuContainer li a").mouseout(
function() {
$(this).removeClass("over");
$("span", this).removeClass('hover');
return false;
});
As pointed out in this post it performs a .find() within the specified selector element.
Hope that helps :)
Damien-at-SF 's answer is fair enough. But I'm thinking it would just add another work.
why not leave your codes as it is and play with the css
.
if you want to style the <span>
's, do it like this,
.menuContainer li a.over span { .... }
.menuContainer li a.over span.hover { .... }
and on my experience, it is best to add/ remove class (to something like this situation) where you can have siblings relation (in this situation, the <li>
's ).
your codes will then be shorten to something like this,
$(".menuContainer li a").mouseover(
function() {
$(this).closest('li').addClass("over").find('span').addClass('hover')
.end().siblings().removeClass("over").find('span').removeClass('hover');
}).append('<span></span>');
精彩评论