以下代码无效。没有类添加到图像。知道为什么吗?感谢您的任何建议。
$(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
答案 0 :(得分: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