2013-05-07 26 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/