jQuery悬停AJAX加载的内容无法正常工作

时间:2015-04-07 00:54:29

标签: jquery html ajax

我通过AJAX获得内容:

<div class="nachricht" id="1">
    bla
    <div class="detail" id="1" style="float: left; display: none;">hidden stuff</div>
    <div class="spacer" style="clear: both;"></div>
</div>

我希望在.details

上悬停时显示.nachricht

所以我用:

$(".nachricht").hover(function(){
    $(".detail", this).stop(true,true).delay(500).show(0);
    }, function (){
    $(".detail", this).stop(true,true).delay(500).hide(0);
});

为什么在通过AJAX加载时它不起作用,我该如何解决?

修改

我从以下函数中获取内容:

function loadfile(){
    $.ajax({
        type: 'post',
        url: 'donachrichten.php',
        data: {mach: "loadfile", kontaktfile: kontaktfile},
        success: function(data){
             $("#chatnow").html(data);
        }
    });
}

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

 $("#chatnow").on('mouseenter', '.nachricht', function( event ) {
    $(".detail", this).stop(true,true).delay(500).show(0);
}).on('mouseleave', '.nachricht', function( event ) {
    $(".detail", this).stop(true,true).delay(500).hide(0);
});

<强>解释

由于.nachricht类项目在您加载页面时不存在,因此您无法将事件与不存在的元素绑定。而是在元素#chatnow上使用事件委托应该有效。

Here are some more example of hover event delegation

答案 1 :(得分:1)

为什么不用css处理show / hide?首先,从.detail div中删除内联样式,然后将其添加到样式表中。

.detail {float:left;display:none}
.nachricht:hover .detail {display:block;}

否则将初始悬停功能包装在一个函数中。

function showDetails(){
$(".nachricht").hover(function(){
    $(".detail", this).stop(true,true).delay(500).show(0);
}, function (){
    $(".detail", this).stop(true,true).delay(500).hide(0);
});
}

并在加载数据后调用它。

success: function(data){
         $("#chatnow").html(data);
         showDetails();
    }