开发者

How do I do a loop in JQuery?

<script>
  $(function() {
    $('#slideshow').crossSlide({
      sleep: 2,
      fade: 1
    }, [
      { src: 'picture1.jpg' },
      { src: 'picture2.jpg' },
    ])
  });
</script>

In this script, I apply a crossSlide effect to #slideshow. However, what if I have 20 divs, and I want to apply the crossSlide effect to each div with the class "slideshow"?

How do I loop through the divs, find th开发者_运维技巧e ones with the class .slideshow, and apply the respective image to each?

Edit: Each div has its own image that I want to show.


Use a class selector combined with an element selector.

$('div.slideshow').crossSlide

Then you will have to use .each() on the elements and get the current object using $(this)


$(function() {
    $('.slideshow').each(function(index,elem) {
        $(this).crossSlide({
            sleep: 2,
            fade: 1
        }, [
            { src: 'picture'+index+'A.jpg' },
            { src: 'picture'+index+'B.jpg' },
        ])
    });
});

You can make the image source filename a function of the current element. You might choose the filename based on the index, an attribute on that element, or something like that.

Otherwise, you have to write it out all 20 times if there's no pattern in your filenames.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜