开发者

Jquery- getting image dimensions in a .each loop?

I'm trying to write some code that will print out the dimensions of all images contained in a div, simple as it seems I can't get it working. Could anyone point out the errors here? Thanks!

$(document).ready(function() {

  var width = 0;
  var height = 0;
  var hello = "hello";

  $('#imagebox img开发者_运维百科').each(function(){

    width = $(this).width;
    height = $(this).height;
    $('#main').append(hello);
    $('#main').append(width);
    $('#main').append(height);    
  });

});

JSBin Example Here


width and height are functions. Try:

width = $(this).width();
height = $(this).height();


There are no attributes widht and height. What you can do is

width = $(this).css('width');

or

width = $(this).width();

and similarly for height.


You should do this after the image has fully loaded.

To do this, can place the code in a .load() handler.

var main = $('#main');

$('#imagebox img').load(function(){
  var $th = $(this);
  width = $th.width();
  height = $th.height();
  main.append((hello + width) + height);   
});

or if you want to make sure that the image dimensions are appended in the proper order, then do it on window load.

$(window).load(function() {
    var main = $('#main');

    var vals = $('#imagebox img').map(function(){
      var $th = $(this);
      width = $th.width();
      height = $th.height();
      return (hello + width) + height;   
    }).get();

    main.append( vals.join('') );
});


I've modified your version to

  • use the proper methods for height and width

  • stop re-querying the DOM for the same elements over and over

  • stop calling append repeatedly

See http://jsbin.com/ikoge5/15/edit

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜