jquery hover not working on my list items

2019-07-31 08:21发布

I am going thru a strange problem,I added hover function to my list items which are generated dynamically using ajax, but nothing is happening.The code is executing without any errors but with no effect.Even the alert is not displaying for mouseenter and mouseout.The alert pops up once in a while but not everytime.I am using the following code.

$('.category_list li').live("mouseenter", function() { 
alert('I m here');
  $(this).find('.category_list').css('text-decoration','underline');
}).live("mouseleave", function() {
alert('I m gone');
  $(this).find('.category_list').css('text-decoration','none');
}); 

My html code is

htmlData.push('<ul class="category_list">');
htmlData.push('<li><a href="javascript:void(0);" onclick="callGetApplicationDetails('+iIndex+',0);" >'+categoryName+'</a></li>');

Please help me since i am stuck very badly.

thanks Hemish

3条回答
我只想做你的唯一
2楼-- · 2019-07-31 08:42

Try using the mouseover and mouseout events. I believe your filtering selector was looking for the <li> elements parent?

$('.category_list li').live('mouseover mouseout', function(event) {
    if (event.type == 'mouseover') {
        alert('I m here');
        $(this).parent().css('text-decoration','underline');
    } else {
        alert('I m gone');
        $(this).parent().css('text-decoration','none');
    }
});

and you could probably clean up the jQuery a little with a new css class

.category_list.over
{
    text-decoration: underline;
}

and use toggleClass()

$('.category_list li').live('mouseover mouseout', function(event) {
    if (event.type == 'mouseover') { alert('I m here'); } 
    else { alert('I m gone'); }

    $(this).parent().toggleClass('over');
});
查看更多
成全新的幸福
3楼-- · 2019-07-31 08:50

Finally! I used livequery and it worked!

$('.category_list li').livequery("mouseenter", function() {
    $(this).css({'background-color' : '#A9A8A8'})
}).livequery("mouseleave", function() {
    $(this).css({'background-color' : '#F4F4F4'})
});

@Patrick:Thanks for the help.

Hope it will help others also.

查看更多
迷人小祖宗
4楼-- · 2019-07-31 08:51

If you don't need to support IE6 with this feature, use CSS instead:

Example: http://jsfiddle.net/QLsQp/

.category_list li a {
    text-decoration:none;
}

.category_list li:hover a {
    text-decoration:underline;
}

This uses the :hover pseudo selector to affect the nested a element when a li is hovered.


The trouble with your javascript is that this:

$(this).find('.category_list')

...won't find anything, because .category_list is an ancestor of the <li> elements, not a descendant.

You would need this instead:

$(this).find('a')
查看更多
登录 后发表回答