What I’m trying to do here is loop through a list of images with jquery .each() and test if the src that I’m passing to the function already exists inside the list. If it doesn’t I want to add it, if does I don’t want to do anything. Where do I put the code to add a new image baring in mind I only want to do this after the each() iterations are over
Here’s what I have so far
function addFriendImage(imageSrc){ //Adds the image of the friend to the sidebar
var imgReturn = $('ul.friendImages li img').each(function(){
var currentImageSrc = $(this).attr('src');
if(currentImageSrc == imageSrc){
return false;
}
});
if(imgReturn != false){//does this make sense?
//I'll add an new image, (I can work out to do this bit myself)
}
}
I’m new to javascript and jquery so I may have gone wrong with the syntax.
Any feedback would be greatly appreciated.
You can skip the loop and just find all images with the src attribute you’re looking for, using the jQuery
[attribute="value"]selector:You can’t return values from
$.eachas it always returns the jQuery object for call chaining. However, returning true/false does have special meaning: Returningfalsebehaves like abreak;statement and iteration stops, while returningtruebehaves like acontinuestatement, stopping the current iteration early and continuing to the next.