开发者

jQuery Hover on <li>

I 开发者_运维技巧have a list of elements like

<ol>
<li class="blah">some text <a href=#">test</a></li>
<li class="blah">some text <a href=#">test</a></li>
<li class="blah">some text <a href=#">test</a></li>
<li class="blah">some text <a href=#">test</a></li>
<li class="blah">some text <a href=#">test</a></li>
<li class="blah">some text <a href=#">test</a></li>
<li class="blah">some text <a href=#">test</a></li>
<ol>

I want to add a hover element so when the user hovers over the <li> then only that items <a> hovers.

I have this (where hover-enabled is just a color)

jQuery('ol li').hover(function () {
    jQuery('ol li.blah a').addClass('hover-enabled');
}, function () {
    jQuery('ol li.blah a').removeClass('hover-enabled');
});

It works but ALL of the <a> items hover - not just the individual <li>. Any ideas ?


Because that ol li.blah a selector is true for all of the list items a elements.

This is assuming you want the class applied to the a element and not the li element.

jQuery('ol li').hover(function () {
    jQuery("a", this).addClass('hover-enabled');
}, function () {
    jQuery("a", this).removeClass('hover-enabled');
});

If you want the li to have the class then use:

jQuery('ol li').hover(function () {
    jQuery(this).addClass('hover-enabled');
}, function () {
    jQuery(this).removeClass('hover-enabled');
});


it's because in your example you are referencing all of them, you instead want to use this.

jQuery('ol li').hover(function () {
    jQuery(this).addClass('hover-enabled');
}, function () {
    jQuery(this).removeClass('hover-enabled');
});


use this instead:

jQuery('ol li').hover(function () {
    jQuery(this).addClass('hover-enabled');
}, function () {
    jQuery(this).removeClass('hover-enabled');
});


If anyone has any problem getting this to work you might need to move the code to the end or wrap it in to an document ready function like this:

$(document).ready(function () {
    jQuery('ol li').hover(function () {
        jQuery(this).addClass('hover-enabled');
    }, function () {
        jQuery(this).removeClass('hover-enabled');
    });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜