我有这个 JSON Facebook Graph API 请求成功部分的例子,
success: function(res){
console.log(res);
$(res.data).each(function(index, value){
var pic = 'https://graph.facebook.com/' + value.id + '/picture?width=200&height=200';
$('<img class="hover" src="'+pic+'" width="200" height="200">').load(function(){
$(this).appendTo("#results").fadeIn("fast");
$(this).wrap('<a href="http://facebook.com/'+value.id+'" target="_blank"></a>');
})
});
},
查找接收到的数据对象,将 page-id 图片放在 img 标签中,当它已经加载时,它将它附加到 #results
div。
但是我无法控制 img .hover
元素。我试过
$("img.hover").hover(function(){
$(this).fadeOut() //for example
});
什么也没有发生。我怀疑这是因为在创建文档时确实存在任何 img。那么,如何获得这些新元素呢?
最佳答案
您需要使用 event delegation , .hover()方法是注册mouseenter的快捷方式和 mouseleave事件如此
$(document).on('mouseenter', 'img.hover', function () {
$(this).fadeIn() //for example
}).on('mouseleave', 'img.hover', function () {
$(this).fadeOut() //for example
});
关于javascript - 通过 .ajax() 请求添加动态 HTML 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22432058/