【发布时间】:2015-08-29 07:38:02
【问题描述】:
我有一个带有轮播的页面,每次幻灯片更改时都会发送一个 ajax 请求,并将与幻灯片相关的产品生成到底部的另一个轮播中。
在每张幻灯片更改的那一刻,使用 Ajax 成功绘制了产品,但我需要在加载 ajax 请求后使用产品启动滑块。现在滑块尝试在请求完成之前进行初始化。
在我添加的代码的底部,每个函数将每个 getProducts 函数添加到一个数组中,然后当它完成时,它应该初始化滑块。虽然在控制台中,消息“this is initialized”发生在 Ajax 请求中的“成功”消息之前。
我是否在这个例子中使用了延迟错误导致了这个问题?
var products = [],
uniqueProducts = [],
defs = [];
var el;
$('.your-class [data-slick-index="' + currentSlide + '"] a').each(function(i) {
el = $(this).attr("href");
products.push(el);
$.each(products, function(j, el) {
if ($.inArray(el, uniqueProducts) === -1)
uniqueProducts.push(el);
console.log("pushed" + uniqueProducts);
});
});
function getProducts(el) {
var def = new $.Deferred();
var url = el;
$.get(url, function(data) {
var imageArray = data.match(/<img itemprop="image" [\S\s]*?>/ig);
var $image = $(imageArray[0]);
var imageUrl = $image.attr('src');
var name = $image.attr('title');
var priceArray = data.match(/<p class="price">[\S\s]*?<\/p>/ig);
var priceEl = $(priceArray[0]).find('[itemprop=price]');
priceEl.children().remove();
var price = priceEl.text() ? '$' + priceEl.text() : '';
$( ".carousel2" ).append( '<div><img src=\" '+ imageUrl +'\"></div>');
console.log("success");
def.resolve();
});
return def.promise();
}
$.each(uniqueProducts, function(i, el) {
defs.push(getProducts(el));
});
$.when($,defs).done(function () {
$('.carousel2').slick({ speed: 500, autoplay: false, autoplaySpeed: 4000, arrows:false });
console.log("this is initialized");
});
}
【问题讨论】:
-
需要在最后一个函数$.when.apply($,defs).done(function () { $('.carousel2').slick( { speed: 500, autoplay: false, autoplaySpeed: 4000, arrows:false }); console.log("this is initialized"); });
标签: javascript jquery ajax jquery-deferred