单击动态添加图像上的事件

时间:2013-08-08 13:28:31

标签: javascript jquery html css ajax

我正在使用此脚本从文件夹生成图像:

$(document).ready(function() {
$.ajax({
    url: "gallery_images",
    success: function(data){
        $(data).find("a:contains(.jpg),a:contains(.gif),a:contains(.png)").each(function(){
            // will loop through
            var images = $(this).attr("href");

            $('<div class="g_image"></div>').html('<img class="g_img" src="gallery_images/'+images+'"/>').appendTo('#galerija');
        });
    }
});

});

问题是,然后我试图点击图片,简单的jQuery点击事件不起作用。

$(".g_image img").click(function(){
alert("WORKING!");

});

2 个答案:

答案 0 :(得分:5)

为此使用事件委托,您可以取代最近的父文档document.body

$(document.body).on("click","#g_image img",function(){
    alert("WORKING!");
});

答案 1 :(得分:2)

尝试使用委托。

$("body").on("click","#g_image img",function(){
 alert("WORKING!");

});