2013-05-07 33 views
1

嗨,jQuery悬停事件不适用于附加对象通过AJAX。jQuery:悬停事件不适用于附加对象与AJAX请求

我添加<div class="item ..."> ... </div>

Ajax调用:

var jqxhr = $.ajax('{{ path('nextPage_url') }}'+page) 
       .always(function(data) { 
        $("#container").append(data).masonry('reload'); 
       }); 

悬停事件代表团:

我徘徊在.item类元素,它 为预加载数据工作正常,但通过ajax请求添加新的<div>其不工作

 $('.item').hover(
      function(){ 
       $(this).addClass('img-polaroid-shadow').removeClass('img-polaroid'); 
      }, 
      function(){ 
       $(this).removeClass('img-polaroid-shadow').addClass('img-polaroid'); 
      } 
     ); 

感谢

+2

用['。对()'](http://api.jquery.com/on/)与事件代理 – billyonecan 2013-05-07 10:52:58

+0

工作样品试试我('hover',function(){alert(2);});'并且不起作用... – 2013-05-07 11:02:26

回答

2

您需要使用event delegation动态添加元素,所以:

$(document).on(
{ 
    mouseenter: function() 
    { 
     $(this).addClass('img-polaroid-shadow').removeClass('img-polaroid'); 
    }, 
    mouseleave: function() 
    { 
     $(this).removeClass('img-polaroid-shadow').addClass('img-polaroid'); 
    } 
} 
, '.item'); 
+0

感谢Eli,但是你的代码和我的代码有什么不同? – 2013-05-07 11:06:08

+1

您的代码只会在第一次加载页面时,将处理程序绑定到'$(“。item”)'selector所返回的元素。新元素不在该集合中。 – Barmar 2013-05-07 11:24:27

2

这是因为当你应用的事件处理程序和加载页面,之前存在的元素被JavaScript看到,因此它只将处理程序应用于这些元素。

但是,当您将一个项目(元素)附加到该页面时,它不在DOM的列表中。因此,在这种情况下,您需要使用事件委派。

只需使用jQuery的.on().delegate()方法。如果你想知道它是如何工作的,那么go here为一个简单的jQuery教程(不是一个参考,只是一个建议)。

2

以下代码

$(document).on('mouseover','span', function() { 
     $(this).css('color','#CCC'); 
    }); 
    $(document).on('mouseout','span', function() { 
     $(this).css('color','#000'); 
    }); 

上的jsfiddle http://jsfiddle.net/HpL7X/