退出jquery$。每个
为什么退出jquery$。每个,jquery,Jquery,为什么不返回false退出$。下面的每个循环 var Items = { "5340071": { "alt": "Sample text" }, "5333539": { "alt": "Sample text" }, // Etc. }; var viewportBottom = $(window).height() + $(window).scrollTop(); $.each(Items, function(ite
不返回false
退出$。下面的每个循环
var Items = {
"5340071": {
"alt": "Sample text"
},
"5333539": {
"alt": "Sample text"
},
// Etc.
};
var viewportBottom = $(window).height() + $(window).scrollTop();
$.each(Items, function(itemId, objItem) {
$("<img src='/img/1503/4/" + itemId + ".jpg?h=150'>").on('load', function() {
$(document.body).append($(this));
var imageTop = $(this).offset().top;
if (imageTop > viewportBottom) {
console.log('Exit loop'); // Text is printed in console
return false; // This should break the $.each loop, but it doesn't
}
});
});
var项目={
"5340071": {
“alt”:“示例文本”
},
"5333539": {
“alt”:“示例文本”
},
//等等。
};
var viewportBottom=$(窗口).height()+$(窗口).scrollTop();
$.each(项,函数(项ID,对象){
$(“”)。在('load',function()上{
$(document.body).append($(this));
var imageTop=$(this).offset().top;
如果(图像顶部>视口底部){
console.log('Exit loop');//文本在控制台中打印
return false;//这应该会中断$。每个循环,但它不会
}
});
});
请告知。从$的回调中没有返回false
。该代码中的每个
。在由
上的附加的事件处理程序中有一个返回false
通常,当您有一个嵌套回调想要影响外部循环时,您可以设置一个标志并在外部循环中检查它;但这在这里是不可能的,因为在调用处理程序时,$。每个
循环早已完成
如果您的目标是在填充视口之前追加图像,则不能使用$。每个,因为在加载图像之前,您不知道何时停止,这是异步发生的。没关系,我们可以在前一个完成后触发加载下一个
var Items = {
"5340071": {
"alt": "Sample text"
},
"5333539": {
"alt": "Sample text"
},
// Etc.
};
var viewportBottom = $(window).height() + $(window).scrollTop();
var index = 0;
var itemIds = Object.keys(Items);
loadNextImage();
function loadNextImage() {
// Get this item ID
var itemId = itemIds[index++];
// Get the alt text for it
var alt = Items[itemId].alt;
// Create the image WITHOUT a src
var img = $("<img>");
// Apply the alt text
if (alt) {
img.attr("alt", alt);
}
// Hook the load handler BEFORE we set src
img.one('load', function() {
// Append the image to the body
img.appendTo(document.body);
// Do we have more?
if (index < Items.length) {
// Do we have room for more?
var imageTop = img.offset().top;
if (imageTop <= viewportBottom) {
// Yes, load the next one
loadNextImage();
}
}
});
// Now set the src
img.attr("src", "/img/1503/4/" + itemId + ".jpg?h=150");
}
var项目={
"5340071": {
“alt”:“示例文本”
},
"5333539": {
“alt”:“示例文本”
},
//等等。
};
var viewportBottom=$(窗口).height()+$(窗口).scrollTop();
var指数=0;
var itemIds=Object.key(项);
loadNextImage();
函数loadNextImage(){
//获取此项目ID
var itemId=itemIds[index++];
//获取它的alt文本
var alt=Items[itemId].alt;
//创建没有src的映像
变量img=$(“
还要注意上面关于src
的部分,您以前的代码有一个争用条件,如果映像在缓存中,可能会出现这种情况
您没有使用alt
文本,因此我在上面添加了该文本。@t.J.Crowder它在for
中工作,我假设它在$中工作。每个:)@古拉迪奥:它们是完全不同的东西。但是如何重写代码使其工作呢?我已经尝试了一个标志,但也不起作用。@Martin:我不能告诉你如何工作,因为据我所知,你试图做的是不可能的。你试图在将来制造一个事件(图像加载回调)影响当前的循环。该代码的实际目标是什么?只附加尽可能多的图像?@Martin:如果是这样,我发布了一个更新,应该可以让您走上正确的道路。我尝试了您的代码,但它似乎没有启动“加载”功能。@Martin:最后一行出现了一个小错误(现已修复)应该是img.attr(“src”、“/img/1503/4/”+itemId+”.jpg?h=150”);