-2

以下代码不起作用。没有类被添加到图像中。知道为什么吗?感谢您的任何建议。

$(document).ready(function () {    
 var starting_pics = ["AN.gif", "CN.gif", "EN.gif", "GN.gif"];    
 var i = 0;    
 for (i = 0; i < starting_pics.length; i++) {    
 $("<img/>").attr("src", "images/" + starting_pics[i]).load(function () {    
 $(this).appendTo("#main");    
 $(this).addClass(".pics");     
}); 

} 

 $(".pics").click(function () {    
 alert("Whatever");    
});

}); //end ready
4

1 回答 1

0

尝试

$(document).ready(function () {    
    var starting_pics = ["AN.gif", "CN.gif", "EN.gif", "GN.gif"];    
    var i = 0;    
    for (i = 0; i < starting_pics.length; i++) {    
        $("<img/>").attr("src", "images/" + starting_pics[i]).load(function () {    
            $(this).appendTo("#main");    
            $(this).addClass("pics");//when adding a class there is no need to prefix `.`
        }); 

    } 

    //need to use event delegation here since the images are added dynamically
    $("#main").on('click', ".pics", function () {    
        alert("Whatever");    
    });

}); //end ready
于 2013-07-27T15:58:35.223 回答