我有以下代码:
$.each(images, function (intValue, currentElement) {
$("#image").on('load', function () {
if (($("#image").width() < 50) || ($("#image").height() < 50)) {
// do something
} else {
// do something
return false; // not working !!!
}
}).attr("src", currentElement).hide()
.each(function () {
if ($(this).complete) $(this).trigger('load');
});
});
我想在else语句中打破每次迭代,所以我添加return false
,但它不起作用,我认为是因为.on('load', function()....
答案 0 :(得分:2)
这是你在寻找什么?在你的情况下,为什么它不工作是图像加载是异步过程,到图像加载时,循环将完成所有附加的加载事件,它们将触发。在每次迭代中return false
都不起作用,因为尚未加载图像。 fiddle
var imageSources = [
'http://placehold.it/10x10',
'http://placehold.it/25x20',
'http://placehold.it/50x50'
];
var loadImg = function loadImages(images){
$("#image").on('load', function () {
if (($("#image").width() < 50) || ($("#image").height() < 50)) {
debugger;
images.shift();
loadImages(images);
} else {
debugger;
$('#image').attr('src', images[0]);
return false;
}
}).attr("src", images[0]).each(function () {
if ($(this).complete) $(this).trigger('load');
});
}
loadImg(imageSources);
答案 1 :(得分:2)
var imageSources = [
'http://placehold.it/10x10',
'http://placehold.it/25x20',
'http://placehold.it/50x50',
'http://placehold.it/100x500'
];
var $myImage = $('#myImage');
var current = 0; //tracks which url is currently loaded
$myImage.load(function() {
//use $(this) if you need jQuery here also
if (this.width < 50 || this.height < 50) {
++current; //update tracker
this.src = imageSources[current]; //load new item
}
});
$myImage.attr('src', imageSources[0]);
var imgs = document.querySelectorAll('img');
for (var i=0; i<imgs.length; ++i) {
addLoadEvents(i);
}
function addLoadEvents(i) {
imgs[i].addEventListener('load', function(e) {
myImgFunction(this, i, e);
});
}
var done = false;
function myImgFunction(elem, i, e) {
//stop functions from running on items that are to be removed.
if (done) { return false; }
//do whatever you want here...use "removeTheRest" for whatever condition the remaining images need to be removed.
if (i > 2) {
done = true;
removeTheRest(i);
}
}
function removeTheRest(i) {
//get rid of the rest of the images
var imgLength = imgs.length;
for (var j=i; j<imgLength; ++j) {
console.log(j);
imgs[j].parentNode.removeChild(imgs[j]);
}
}