Using jQuery each to grab image height

2019-05-09 23:09发布

问题:

I have a bunch of images on a page. I'm trying to use jQuery to grab the height of each image and display it after the image. So here is my code:



$(document).ready(function() {
  $(".thumb").each(function() {
    imageWidth = $(".thumb img").attr("width");
    $(this).after(imageWidth);
  });
});

<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>

[...]


My logic behind the jQuery is that I want to go through each "thumb" selector, assign the height of the img inside "thumb" to the variable "imageWidth", and then display the height in text after each "thumb".

The problem I'm having is that it's only working on the first image and then quitting. I can get it to work if I use the "thumb_img" class, of course, but I need access to the height of the image for the "thumb" class.

Hopefully this isn't too confusing as I'm fairly new to jQuery. Thanks advance.

回答1:

Use this:

imageWidth = $(this).children("img").attr("width")

The following selects all your images:

$(".thumb img")

... so when you ask for the attribute it returns it from the first object in the collection

Sorry for all the edits... but it is best to reuse jquery objects, so:

var $this = $(this)

Then refer to $this were needed for optimization. Not that big a deal in this example, but it is a good practice to use.



回答2:

You won't be able to use document.ready() to do this as the images will not have loaded by the time that is called.

You actually need to put this code into the onload() event handler, which is called after the document and all images have finished loading.

It is only when the images have finished loading that the browser knows how big they are.



回答3:

$().ready(function() {

        $(".thumb img").load(function() {
            var imageHeight = $(this).height();
            $(this).parent().append(imageHeight);

        });

});


回答4:

I have used something similar to preload an image and set some code in mouseover and mouseout and set the style for all images with a class name "swap". For me $(this) did not work but directly this worked:

// in jquery
$(document).ready(function(){
        swapAndPreload();
    });

function swapAndPreload(){
    $(".swap").each(function(){
        // preload images in cache
        var img = new Image();
        img.src=this.src.replace(/([-_])out/,'$1over');
        //set the hover behaviour
        this.onmouseover = function(){
            this.src=this.src.replace(/([-_])out/,'$1over');
        }
        //set the out behaviour
        this.onmouseout = function(){
            this.src=this.src.replace(/([-_])over/,'$1out');
        }
        //set the cursor style
        this.style.cursor="pointer";
    });
}