jQuery - 将点击事件分配给数组添加的图像

jQuery - Assigning click events to images added by an array

我正在尝试构建一个基于 jQuery 的图片库,使用数组来托管图片缩略图。我已经成功地让图像连续呈现,但是我很难找到一个解决方案来解决如何为数组中的每个图像分配一个唯一的点击事件。

HTML:

<div id="thumbCont"></div>

jQuery/JS:

var thumbImgArray = ["http://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-11/256/thumbs-up.png", "http://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-11/256/thumbs-up-medium-skin-tone.png", "http://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-11/256/thumbs-up-medium-skin-tone.png"]


var $div = $('#thumbCont');
$.each(thumbImgArray, function(i, val) {
        $("<img />").attr("src", val).appendTo($div).css({float: "left", width: "196px", height: "196px", marginRight: "4px", border: "2px solid white", cursor: "pointer"});
 });

这是我的JS Fiddle

如有任何帮助或反馈,我们将不胜感激!

尝试在创建 img 标签时添加 onclick 事件处理程序

var thumbImgArray = ["http://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-11/256/thumbs-up.png", "http://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-11/256/thumbs-up-medium-skin-tone.png", "http://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-11/256/thumbs-up-medium-skin-tone.png"]


var $div = $('#thumbCont');
$.each(thumbImgArray, function(i, val) {

  $("<img id='img_" + i + "' onclick='test(this.id)'/>").attr("src", val).appendTo($div).css({
    float: "left",
    width: "196px",
    height: "196px",
    marginRight: "4px",
    border: "2px solid white",
    cursor: "pointer"
  });
});

function test(imgId) {
  console.log(imgId)

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thumbCont"></div>