所以我试图检查图库中的每个图像并将其与从 php 返回的另一个图像覆盖。我收集所有的 ,然后迭代它们,创建一个“保持框架”,然后将动态图像添加到其中。
不知何故,它们都添加到我处理的最终图像中。每个图像都有一个框架,但新图像都覆盖在图库中的最终图像上。
我做错了什么。我使用 that=this 来处理 AJAX 回调中的范围,
var $allPics = $(".pixelsandwich");
$allPics.each(function(){
$(this).wrap('<div class="pixelsandwichFrame" />');
src = $(this).attr('src');
$that = $(this);
$.ajax({
type:"POST",
url:"js/pixelsandwich/pixelsandwich.php",
data:{src:src},
success:function(response){
newImg = $("<img class='crunched'>");
newImg.attr('src', response);
frame = $that.parent();
frame.append(newImg); // << these are all appending to the frame of the last image instead of each one
}
});
});
最佳答案
您的 $that
是一个全局变量(因为它缺少 var
),因此它在循环的每一步中都会被覆盖。在本地声明:
$(".pixelsandwich").each(function () {
var $that = $(this).wrap('<div class="pixelsandwichFrame" />');
$.ajax({
type: "POST",
url: "js/pixelsandwich/pixelsandwich.php",
data: { src: $that.attr('src') },
success: function (response) {
var newImg = $("<img class='crunched'>").attr('src', response);
$that.parent().append(newImg);
}
});
});
关于javascript - 使用 jQueryeach() 动态添加图像到 div ..不知何故,它们都添加到最后一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14668650/