我在jQuery中有一个函数,当你将鼠标悬停在div上时,它会消失,并在其位置显示另一个div。该函数运行良好,直到我使用Ajax加载项目进行无限滚动。我知道它与绑定新元素有关(从我读过的,使用on()),但由于我是jQuery的新手,我不知道如何实现这个改变。我一直在努力过去几个小时,但没有取得进展。
(具体问题:对于新加载的项目,ajax加载时会破坏new_social悬停)
非常感谢任何帮助,尤其是代码形式!非常感谢!
以下是功能:
$("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
再次感谢!
答案 0 :(得分:-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()方法,所以性能提升可以忽略不计,但在深度嵌套的网站上可能会变得很麻烦。这就是为什么我建议绑定到树内较低的静态内容。