简体   繁体   English

如何在JQuery中进行循环?

[英]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. 在此脚本中,我将crossSlide效果应用于#slideshow。 However, what if I have 20 divs, and I want to apply the crossSlide effect to each div with the class "slideshow"? 但是,如果我有20个div,并且我想将crossSlide效果应用于“ slideshow”类的每个div怎么办?

How do I loop through the divs, find the ones with the class .slideshow , and apply the respective image to each? 如何遍历div,找到类为.slideshow ,然后将相应的图像应用于每个div?

Edit: Each div has its own image that I want to show. 编辑:每个div都有自己要显示的图像。

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) 然后,您将必须在元素上使用.each()并使用$(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. 否则,如果文件名中没有模式,则必须将其全部写入20次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM