0

我有一些 jQuery,它在悬停时为 > 标签的背景颜色设置动画<div(并在不再悬停时恢复它们)。

$('.row').hover(function() {
    $(this).stop().animate({
        backgroundColor: "#000000"
    }, 250 );
}, function () {
    $(this).stop().animate({
        backgroundColor: "#15181A"
    }, 250 );
});

我的页面上有一个 AJAX 调用来加载一些额外<div的 >,如下所示:

$.ajax({
    type : 'POST',
    url : "ajax.php",
    dataType : 'json',
    data: {
        query : $('#search').val()
    },
    success : function(data) {
        if (data.error === true) {
            // Error
        } else {
            $('#more').html(data.msg);
        }
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
        // Error
    }
});

AJAX 调用有效地返回更多<div带有“行”类的 >s,但是当它们悬停时,jQuery 不会为其背景颜色设置动画。是否可以使用 jQuery 选择这些行,即使它们是通过 AJAX 加载的?

编辑:这是 AJAX 调用 ajax.php 返回的内容:

<?php
$return['error'] = false;
$return['msg'] = '<div class="row" style="background: #15181A;">A row...</div>';
$return['msg'] = '<div class="row" style="background: #15181A;">Another row...</div>';
$return['msg'] = '<div class="row" style="background: #15181A;">Another row...</div>';
echo json_encode($return);
return;
?>
4

4 回答 4

3

动态元素需要委托的事件处理程序:

$('#more').on({
    mouseenter: function() {
        $(this).stop().animate({
            backgroundColor: "#000000"
        }, 250 );
    },
    mouseleave: function() {
        $(this).stop().animate({
            backgroundColor: "#15181A"
        }, 250 );
    }
}, '.row');
于 2013-03-20T01:27:05.073 回答
3

将其绑定到您的#more元素。

$("#more").on("mouseenter mouseleave", ".row", function(e){
  if(e.type == "mouseenter"){ 
    // your hover code
  }else{
    // your off-hover code
  }
});
于 2013-03-20T01:27:33.670 回答
0

这可能是因为您在实际向页面附加来自 AJAX 请求的新内容之前调用您的方法来设置悬停效果。

例如这样的事情:

success: function (data) {
    if (data.error === true) {
        // Error
    } else {
        $('#more').html(data.msg);
        $('.row').hover(function () {
            $(this).stop().animate({
                backgroundColor: "#000000"
            }, 250);
        }, function () {
            $(this).stop().animate({
                backgroundColor: "#15181A"
            }, 250);
        });
    }

.row当您在 AJAX 请求成功时附加与选择器匹配的新元素时。

于 2013-03-20T01:27:22.250 回答
0

您需要$('.row').hover(function() ...在您的 AJAX 成功函数中调用 。

于 2013-03-20T01:28:25.330 回答