jQuery Loop through each div

后端 未结 5 789
暗喜
暗喜 2021-02-05 15:10

I\'m pretty sure this will be a really easy answer for you jQuery whizzes, and I\'m also pretty such it involves a loop of some kind.

I\'m trying to perform essentially

相关标签:
5条回答
  • 2021-02-05 15:25

    What about .each()?

    http://api.jquery.com/each/

    0 讨论(0)
  • 2021-02-05 15:25

    Just as we refer to scrolling class

    $( ".scrolling" ).each( function(){
        var img = $( "img", this );
        $(this).width( img.width() * img.length * 1.2 ) 
    })
    
    0 讨论(0)
  • 2021-02-05 15:32

    You're right that it involves a loop, but this is, at least, made simple by use of the each() method:

    $('.target').each(
        function(){
            // iterate through each of the `.target` elements, and do stuff in here
            // `this` and `$(this)` refer to the current `.target` element
            var images = $(this).find('img'),
                imageWidth = images.width(); // returns the width of the _first_ image
                numImages = images.length;
            $(this).css('width', (imageWidth*numImages));
    
        });
    

    References:

    • css().
    • each().
    • find().
    0 讨论(0)
  • 2021-02-05 15:43
    $('div.target').each(function() {
       /* Measure the width of each image. */
       var test = $(this).find('.scrolling img').width();
    
       /* Find out how many images there are. */
       var testimg = $(this).find('.scrolling img').length;
    
       /* Do the maths. */
       var final = (test* testimg)*1.2;
    
       /* Apply the maths to the CSS. */
       $(this).find('scrolling').width(final); 
    });
    

    Here you loop through all your div's with class target and you do the calculations. Within this loop you can simply use $(this) to indicate the currently selected <div> tag.

    0 讨论(0)
  • 2021-02-05 15:44

    Like this:

    $(".target").each(function(){
        var images = $(this).find(".scrolling img");
        var width = images.width();
        var imgLength = images.length;
        $(this).find(".scrolling").width( width * imgLength * 1.2 );
    });
    

    The $(this) refers to the current .target which will be looped through. Within this .target I'm looking for the .scrolling img and get the width. And then keep on going...

    Images with different widths

    If you want to calculate the width of all images (when they have different widths) you can do it like this:

    // Get the total width of a collection.
    $.fn.getTotalWidth = function(){
        var width = 0;
        this.each(function(){
            width += $(this).width();
        });
        return width;
    }
    
    $(".target").each(function(){
        var images = $(this).find(".scrolling img");
        var width = images.getTotalWidth();
        $(this).find(".scrolling").width( width * 1.2 );
    });
    
    0 讨论(0)
提交回复
热议问题