how to get image size from a jquery json parse?
-
29-05-2021 - |
Question
how to get image size from a jquery json parse? I put a each function
, first download all the images to the html part then try to use width()
& height()
to the the image size, but I met some trouble in getting width()
& height()
are ahead of the image loading.
example code in http://jsfiddle.net/7eLj4/
jQuery code:
$(document).ready(function(){
var data = '[{"image":"http:\/\/pcdn.500px.net\/6269271\/a85b2995b4d80748831492be5e8a3689895a2b0e\/4.jpg"},{"image":"http:\/\/pcdn.500px.net\/5953805\/d0dd841969187f47e8ad9157713949b4b95b3bda\/4.jpg"},{"image":"http:\/\/pcdn.500px.net\/5735750\/0dd26cb9f53b7bbbedf1b65c0d0aac013f77466c\/4.jpg"}]';
var obj = $.parseJSON(data);
$.each(obj, function(index,item) {
$('#imagewrap').append('<img class="images" src="'+item.image+'" />');
});
$('.images').each(function(){
var width = $(this).width();
var height = $(this).height();
var imgsrc = $(this).attr('src');
alert(width+''+height+''+imgsrc);
});
});
Html code:
<div id="imagewrap"></div>
Solution
Bind to the image load event:
$('.images').bind('load', function () {
// do something here
});
Here's your fiddle updated to demonstrate: http://jsfiddle.net/7eLj4/5/
OTHER TIPS
Call the function that accesses the .width()
and .height()
of an image from an onload
function for each image. onload
will get called after the image has completed downloading.
myImage.onload = function() {
var accurateWidth = myImage.width();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow