这对我来说很难理解,我不喜欢这个"解决方案",因为它真的不应该解决我的问题。
我有一个函数,40%的时间不完全遵循。起初,我认为这是由于我操纵img和iframe元素在飞行,但我已经做了各种事情,以确保缓存和加载排序之前,他们做他们的事情。
特别地,我对newCover
变量所做的事情只有60%的时间自己执行。在我的挫折中,我在函数的末尾记录了newCover
,试图理解为什么它有时不出现。
但奇怪的是,因为我是控制台记录变量,我得到100%的成功率与函数做它应该做的。
为什么?
你可以在这里看到它在第三篇文章中工作:http://syndex.me
代码如下:
albumCover = function(){
$(".forPhotoset").each(function () {
var forPhotoset = $(this);
var myFrame = forPhotoset.find("iframe");
myFrame.hide();
myFrame.load(function(){
var newCover = myFrame.contents().find('.photoset').children(':first-child').children(':first-child');
newCover.children(':first-child').remove();
var psPre = newCover.attr("href")+ '?' + (Math.random() * 1);
newCover.append("<img src='"+ psPre +"' alt='Cover Page' />");
var psHeight = newCover.find('img');
psHeight.load(function(){
if (psHeight.height()>heightRef){
psHeight.height(heightRef);
}
})
newCover.detach();
forPhotoset.append(newCover); //only executes 60% of the time
console.log(newCover);//i added this, now i get 100% success rate?!
})
});
}
只是一点猜测,但可能是console.log调用略微减慢了脚本的计时速度,并允许其他dom更改有更多时间完成。也许可以尝试将调用包装在setTimeout()中,看看这是否与console.log调用具有相同的效果。