我正在使用一个使用AJAX显示文章的wordpress网站。我在成功回调中添加了一些jquery代码。我的一个需求是在鼠标上显示图像。我的所有代码都有效,除了鼠标效果。
所以这是我的ajax功能:
function loadArticle(pageNumber, loop, term){
$.ajax({
url: ajax_var.url,
type:'POST',
data: someData,
success: function(html){
// This will be the div where our content will be loaded
$("#content").append(html);
// Zoom box
$('img.static').hide();
$(".ad-preview").live({
mouseover: function() {
$(this).find('img.static').stop().fadeIn();
},
mouseout: function() {
$(this).find('img.static').stop().fadeOut();
}
});
// Other stuff...
});
return false;
}
});
和HTML:
<div class="ad-preview">
<a target="_blank" href="">
<img src="img/zoom.png" /></a>
</a>
</div>
实现此效果的好方法是什么?
答案 0 :(得分:2)
.live是由.on
取代的主动侦听器你可以将它放在ajax调用之外,在js的基本级别 - 换句话说,不是在document.ready调用内部或在其他函数内部。它将适用于通过ajax加载的dom元素。
答案 1 :(得分:2)
首先,您应该使用on而不是live
。其次,委托处理程序不必在回调中应用。因为它们被委托给页面上保留的更高级别元素,所以您可以在页面加载时应用它们。
$("body").on('mouseover', '.ad-preview', function() {
$(this).find('img.static').stop().fadeIn();
})
.on('mouseout', '.ad-preview', function() {
$(this).find('img.static').stop().fadeOut();
});