2013-02-21 66 views
0

我在jQuery中有一個函數,當您將鼠標懸停在div上時,它會消失並在其位置顯示另一個div。該函數運行良好,直到我加載項目使用Ajax進行無限滾動。我知道它與綁定新元素有關(從我讀過的內容,使用on()),但由於我是jQuery新手,我不知道如何實現這一變化。我一直在嘗試過去幾個小時,但沒有取得任何進展。無限滾動打破jQuery事件

(具體問題:new_social懸停被打破對新加載的項AJAX負荷)

任何幫助將是非常讚賞,尤其是在代碼的形式!非常感謝!

這裏的功能是:

$("a.share").hover(function(){ 
    $(this).closest($('div.new_story')).children("div.new_social_buttons").show(); 
    $(this).closest(".new_social").hide(); 
}, 
function(){ 
    }); 


$("div.new_social_buttons").hover(function(){ 

}, 
function(){ 
    $(this).hide(); 
    $(this).closest($('div.new_story')).children("div.new_social").show(); 
}); 

這裏是AJAX加載功能:

jQuery.ias({ 
container : '#middle', 
item: '.new_story', 
pagination: '#pagination', 
next: 'a.next', 
loader: '<img src="loader.gif"/>', 
history: false 

}); 

這裏就是我得到了無限滾動,我覺得它有jQuery的函數調用的背後: https://github.com/webcreate/Infinite-Ajax-Scroll

再次感謝!

回答

-1

這聽起來像事件需要委託給頁面加載期間存在的靜態父元素。

委派a.share處理器

$(document).on({ 
    mouseenter: function(){ 
     $(this).closest($('div.new_story')).children("div.new_social_buttons").show(); 
     $(this).closest(".new_social").hide(); 
    }, 
    mouseleave: function(){ 
     //looks like nothing going on here; just providing for future ref. 
    } 
}, 'a.share'); 

委派div.new_social_buttons處理器

$(document).on({ 
    mouseenter: function(){ 
     //looks like nothing going on here; just providing for future ref. 
    }, 
    mouseleave: function(){ 
     $(this).hide(); 
     $(this).closest($('div.new_story')).children("div.new_social").show(); 
    } 
}, 'div.new_social_buttons');  

當使用.on()您不能正常使用的.hover()包裝方法。相反,您必須提供一個mouseenter and mouseleave對象,並在其中聲明該功能。

此外,重要的是要注意,您應該用任何靜態父元素替換document以保存性能。因爲jQuery的委託選擇器利用javascript的querySelectorAll()方法,所以性能增益可以忽略不計,但可能會在深度嵌套網站上變得繁重。這就是爲什麼我建議綁定到靜態樹中更低的東西。

+0

謝謝!這似乎奏效了! – Nicky316 2013-02-22 00:13:38

+0

任何機會,你知道什麼代碼將在鼠標的第一部分內加載在div內的Facebook和Twitter按鈕? – Nicky316 2013-02-22 03:42:26