开发者

Testing Inside .each() and breaking out

开发者 https://www.devze.com 2023-01-29 08:32 出处:网络
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,

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:

function addFriendImage(imageSrc){ //Adds the image of the friend to the sidebar

    if ($('ul.friendImages li img[src="' + imageSrc + '"]').length) {
       // img with src attribute matching imageSrc exists
    } else {
       // img doesn't exist
    }

}

You can't return values from $.each as it always returns the jQuery object for call chaining. However, returning true/false does have special meaning: Returning false behaves like a break; statement and iteration stops, while returning true behaves like a continue statement, stopping the current iteration early and continuing to the next.


You can avoid all the extra stuff and query it directly.

if(!($('ul.friendImages li img[src=' + imageSrc + ']').length)){
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号