如何在 JQuery 中进行循环?

发布于 2024-10-05 07:05:40 字数 452 浏览 0 评论 0原文

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

在此脚本中,我将 crossSlide 效果应用于#slideshow。 但是,如果我有 20 个 div,并且我想将 crossSlide 效果应用到类为“slideshow”的每个 div 该怎么办?

如何循环遍历 div,找到类 .slideshow 的 div,并将相应的图像应用于每个 div?

编辑:每个 div 都有我想要显示的自己的图像。

<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 the ones with the class .slideshow, and apply the respective image to each?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

永不分离 2024-10-12 07:05:40

使用 类选择器元素选择器

$('div.slideshow').crossSlide

然后,您必须在元素上使用 .each() 并使用 $(this) 获取当前对象

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)

云淡风轻 2024-10-12 07:05:40
$(function() {
    $('.slideshow').each(function(index,elem) {
        $(this).crossSlide({
            sleep: 2,
            fade: 1
        }, [
            { src: 'picture'+index+'A.jpg' },
            { src: 'picture'+index+'B.jpg' },
        ])
    });
});

您可以使图像源文件名成为当前元素的函数。您可以根据索引、该元素的属性或类似的内容来选择文件名。

否则,如果文件名中没有模式,则必须将其全部写出 20 次。

$(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文