这对我来说很难理解,我不喜欢“解决方案”,因为它真的不应该解决我的问题。
我有一个功能,但 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 调用具有相同的效果。
关于javascript - 为什么以及如何在 console.log 中引用变量来修复我遇到的加载错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8461404/