1

我要解决一个奇怪的问题,我在使用 ajax 动态生成的列表项中添加了悬停功能,但没有发生任何事情。代码正在执行,没有任何错误,但没有效果。即使是 mouseenter 和 mouseout 的警报也没有显示.警报偶尔会弹出一次,但不是每次都弹出。我正在使用以下代码。

$('.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');
}); 

我的html代码是

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

请帮助我,因为我被困得很厉害。

谢谢赫米什

4

3 回答 3

2

尝试使用mouseoverandmouseout事件。我相信您的过滤选择器正在寻找<li>父元素?

$('.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');
    }
});

你可能可以用一个新的 css 类来清理一下 jQuery

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

并使用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');
});
于 2011-02-25T18:20:17.223 回答
0

如果您不需要通过此功能支持 IE6,请改用 CSS:

示例:http: //jsfiddle.net/QLsQp/

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

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

这使用:hover伪选择器在 a悬停a时影响嵌套元素。li


您的 javascript 的问题在于:

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

...不会找到任何东西,因为.category_list是元素的祖先<li>而不是后代

你会需要这个:

$(this).find('a')
于 2011-02-25T18:24:15.307 回答
0

最后!我使用了livequery,它奏效了!

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

@Patrick:感谢您的帮助。

希望它也能帮助其他人。

于 2011-02-25T21:43:40.487 回答