Javascript 使用相同的类为每个div运行脚本

Javascript 使用相同的类为每个div运行脚本,javascript,jquery,html,Javascript,Jquery,Html,嗯,我在跑步。所以我必须通过jQuery设置DIV的高度和宽度。这是摄影师的作品集,所以我有上千张不同大小的照片 HTML JavaScript: <script type="text/javascript"> var width = 0; $('.cesco1 img').each(function() { width += $(this).outerWidth( true ); alert(width); }); $('.cesco1').css('width', width +

嗯,我在跑步。所以我必须通过jQuery设置DIV的高度和宽度。这是摄影师的作品集,所以我有上千张不同大小的照片

HTML

JavaScript:

<script type="text/javascript">
var width = 0;
$('.cesco1 img').each(function() {
width += $(this).outerWidth( true );
alert(width);
});
$('.cesco1').css('width', width + 0);
</script>
我对高度也使用相同的JavaScript。 第一个拇指宽度为300px,第二个拇指宽度为200px。 所以我得到了一个500px宽的div,它加起来。 我想在当时设置每个DIV的宽度。 我是新手,如果它是哑的,很抱歉。

请使用最接近的方法访问包含图像的DIV

$('.cesco1 img').each(function() {
    width += $(this).outerWidth( true );
    alert(width);
    $(this).closest('.cesco1').css('width', width);
});
如果图像始终是DIV的直接子对象,则可以使用效率更高的选择器.cesco1>img和.parent,而不是.closest.cesco1.

尝试以下操作:

<script type="text/javascript">
    $(function(){
        $('.cesco1').each(function() {
          var width = 0;
          $(this).children('img').each(function(){ 
              width += $(this).outerWidth( true );  // reset the width
          });
          $(this).css('width', width);
        });
    });
</script>
<script type="text/javascript">
    $(function(){
        $('.cesco1').each(function() {
          var width = 0;
          $(this).children('img').each(function(){ 
              width += $(this).outerWidth( true );  // reset the width
          });
          $(this).css('width', width);
        });
    });
</script>