开发者

How to send a parameter to the each function in Jquery

开发者 https://www.devze.com 2023-03-06 15:55 出处:网络
I\'m trying to paginate an image gallery using jquery. The image directory I\'m using contains about 600 images, named like th开发者_开发百科is: \"photo1.jpg\" ... \"photo(n).jpg\" ... \"photo600.jpg\

I'm trying to paginate an image gallery using jquery. The image directory I'm using contains about 600 images, named like th开发者_开发百科is: "photo1.jpg" ... "photo(n).jpg" ... "photo600.jpg".

Suppose I have a variable holding the page number var page and there are 40 images on each virtual page. I want to do something like:

for (var i = 0; i<40; i++){
      var imageNum = (((page*40)-40)+i+1);
      $("img")[i].attr("src","photo"+ imageNum + ".jpg"); // Doesn't work
   }
}

This is hackish but do you see what I am trying to do? The jquery API had some info on using each() to iterate through a jquery object but i couldn't figure out how to send the each function a parameter holding data about which page I am on, which I will need to determine the paths to the images. I'm going for something like:

$("img").each(function (i) {
        //code to update image paths based on page parameter
      });

I'm open to different approaches as well, I am a total noob and I feel like I might be going about this in the wrong way to begin with :S.

Edit Thanks to everyone for their answers.

If you are looking for a quick and simple answer that works using each(), check out Jeff B's answer.

I accepted patrick dw's answer because it goes into a bit more detail about a separate mistake I was making and covers another approach as well. Also, please see our comments on his response if you are like me and thought you needed to pass parameters to .each().


This doesn't work because [i] gives you a native DOM element that is not wrapped in a jQuery object.

jQuery has the eq()[docs] method to give you the element wrapped so you can call the attr()[docs] method.

   // Do NOT run the selector inside the loop
var imgs = $("img");

for (var i = 0; i<40; i++){
      var imageNum = (((page*40)-40)+i+1);
      imgs.eq( i ).attr("src","photo"+ imageNum + ".jpg"); // Doesn't work
   }
}

As an alternative, you can pass a function directly to the attr()[docs] method that will loop over the elements for you.

$("img").attr( 'src', function(i) {
    return "photo" + (((page*40)-40)+i+1) + ".jpg";
});

The return value is the value that will be assigned to the attribute you're setting (which is src in this case).


The .each() function passes an index, (and value if you desire) for you:

$("img").each( function(idx) {
    $(this).attr("src","photo"+ (((page*40)-40)+idx+1) + ".jpg");
});

Example: (similar, but modified to use placeholders)

http://jsfiddle.net/mEzR9/


Second approach is more pretty of course but first one will also work.

You should use this: $($("img")[i]).attr(...)

0

精彩评论

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