I am trying to set DIV width based on the child image. This code below works if there is only one DIV. When there are more, it will only use the width of the first child image (first DIV).
$('.img_thumb').each(function(){
$('img').load(function(){
var img_width = $('.img_thumb img').width();
$('.img_thumb').css('width', img_width + 'px');
});
});
Any help would be开发者_开发技巧 appreciated. Thanks
In the .load()
callback, use this
to refer to the specific image of interest. Get rid of the .each()
.
$('img').load(function(){
var $this = $(this),
img_width = $this.width();
$this.closest('.img_thumb').css('width', img_width + 'px');
});
On line 3 you have a reference to the object $('.img_thumb img')
:
var img_width = $('.img_thumb img').width()
Which is always going to point to the first element. You need to use $(this)
when you're inside the .each
in order to target the current element:
var img_width = $(this).width()
Try this:
$('.img_thumb').each(function(){
var _this = $(this);
$(this).find('img').load(function(){
_this.css('width', $(this).width() + 'px');
});
});
精彩评论