JQuery用ajax调用和承诺嵌套每个循环?
上下文-我的页面动态加载许多div容器,其中加载了1或2个图像,但这些图像是隐藏的。加载所有隐藏图像后,我将使用waitForImages JQuery插件来确保循环遍历每个容器和每个容器中的每个图像,并向php函数发送ajax调用,该函数确定图像中的主色像素。当此ajax调用返回颜色(如果有两个图像)时,脚本将容器设置为该颜色/这些颜色 如果我强制ajax调用同步工作,我会让它工作得很好,但是当有很多图像要浏览时,这会冻结我的页面,这是可以想象的。我真的可以用它来装载容器,然后在页面上进行交互,同时更新背景中的容器颜色 以下是其中一个容器的示例,在此过程完成后,应用背景色:JQuery用ajax调用和承诺嵌套每个循环?,jquery,ajax,Jquery,Ajax,上下文-我的页面动态加载许多div容器,其中加载了1或2个图像,但这些图像是隐藏的。加载所有隐藏图像后,我将使用waitForImages JQuery插件来确保循环遍历每个容器和每个容器中的每个图像,并向php函数发送ajax调用,该函数确定图像中的主色像素。当此ajax调用返回颜色(如果有两个图像)时,脚本将容器设置为该颜色/这些颜色 如果我强制ajax调用同步工作,我会让它工作得很好,但是当有很多图像要浏览时,这会冻结我的页面,这是可以想象的。我真的可以用它来装载容器,然后在页面上进行交互
<div class="image_product" style="background-color: rgb(186, 214, 78);" onclick="view_product(27);">
<img style="display:none;" src="/module_uploads/image_replacer/23/110914130755_0_94.jpg">
<img style="display:none;" src="/module_uploads/image_replacer/13/180614104219_0_94.jpg">
<div class="product_grid_heart_container" style="border-top-color: rgb(255, 255, 255) !important; background-color: rgb(239, 63, 63);">
<div class="product_grid_heart"> AK/H </div>
</div>
</div>
就像我说的那样,它可以完美地工作,它只是冻结了我无法拥有的页面。我相信答案在于承诺,但尽管我发现这些例子很有意义,但我真的很难将它们应用到我的情况中,最终我完全不知所措。非常感谢您的帮助 你的承诺是什么意思?据我所知,你正在执行div.image\u产品元素的所有操作。因此,一个$'div.image_product'.promisefunction{//your code here};应该是您正在寻找的。@DevlshOne您能给我一个示例,说明您将如何执行此操作/与每个循环相关的操作情况吗?@Hello如果您要创建一个JSFIDLE来表示您的场景,我很乐意为您标记它。
$('div.image_product').each(function() {
var colors = [];
$(this).find('img').each(function() {
var img = $(this).attr('src');
var sanitised_img1 = img.replace(/\//, "");
var sanitised_img = sanitised_img1.replace(/\//g, "***");
$.ajax({
async: false,
type: "POST",
url: '/general/dominant_colour/'+sanitised_img+'/rgb',
success: function(dominant_colour) {
colors.push(dominant_colour);
}
});
});
if($(this).find('.secondary_cat_image').length > 0)
{
$(this).find('.product_grid_heart_container').css({"background-color": "rgb(" + colors[0] + ")"});
}
else
{
$(this).css("background-color", "rgb(" + colors[0] + ")");
if(colors.length > 1)
{
$(this).find('.product_grid_heart_container').css({"background-color": "rgb(" + colors[1] + ")"});
}
else
{
$(this).find('.product_grid_heart_container').css({"background-color": "rgb(" + colors[0] + ")", "border-top-color": "rgb(" + colors[0] + ")"});
}
}
});