【问题标题】:How to loop through each image with the same class name? [duplicate]如何遍历具有相同类名的每个图像? [复制]
【发布时间】:2012-12-29 02:52:40
【问题描述】:

可能重复:
jQuery to loop through elements with the same class

我正在尝试遍历具有类的图像。

for(var i=0; i<sizes.length; i++){
    var imageSize=sizes[i];
    $('.image').width(imageSize);
}

我有 10 个具有相同类名的图像,但是,我希望它们具有不同的图像大小。

循环会循环 10 次,但我不确定如何让每个图像都有特定的imagesize

有人可以帮我吗?我的大脑快要炸了。非常感谢!

【问题讨论】:

  • 你的问题一点都不清楚。什么是尺寸,你有多少图像?你想做什么?
  • 记住:$(selector) 匹配所有具有该选择器的元素。所以你有一个你试图设置宽度的图像集合,并且 jQuery 要求。

标签: javascript jquery


【解决方案1】:

如果您的所有图像都有.image 类,您可以简单地执行以下操作

$( '.image' ).each( function ( index ) {
    $( this ).css( 'width', sizes[ index ] );
});

【讨论】:

    【解决方案2】:

    你可以这样做:

    $('.image').each(function(i) {
        $(this).width(sizes[i]);
    });
    

    但您必须确保 size 数组包含正确的尺寸,与图像在页面上出现的顺序相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      相关资源
      最近更新 更多