发现尺寸动态加载,但使用jQuery的DOM追加形象? [英] find the dimensions of a dynamically loaded but DOM-appended image using jquery?
问题描述
我在动态使用AJAX,其中取值
是这样的源加载图像的来源。我创建了DOM图像元素,一旦它的加载它分配这个来源,然后将其附加到 DIV
名为 imgwrapper
。然后我试图让图像的尺寸,但它不工作。我知道你不能得到的图像多数民众赞成动态加载的尺寸,而不是即使被追加到DOM?
I'm loading the source of an image dynamically using ajax, where s
is this source. I create an image element in the DOM, assign it this source once it's loaded, and then append it to a div
called imgwrapper
. Then I try to get the image's dimensions, but it doesn't work. I'm aware you can't get the dimensions of an image that's dynamically loaded, but not even after being appended to the DOM?
我的code是如下:
//use ajax to get value of s (the image source)
img = document.createElement("img");
img.src = s;
$('#imgwrapper').appendChild(img);
console.log($('#imgwrapper').find('img').width());
这将返回,而不是给我的图像的宽度0。
this returns 0, instead of giving me the image's width.
推荐答案
等到图像完成加载
//use ajax to get value of s (the image source)
img = document.createElement("img");
img.onload = function() {
console.log($('#imgwrapper').find('img').width());
};
img.src = s;
$('#imgwrapper').append(img);
修改
由于@MattiasBuelens提及。没有 .appendChild()
的jQuery对象。这应该是 .append()
而不是
Edit
As @MattiasBuelens mentioned. There is no .appendChild()
for a jQuery object. That should be .append()
instead
这篇关于发现尺寸动态加载,但使用jQuery的DOM追加形象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!