发现尺寸动态加载,但使用jQuery的DOM追加形象?加载、尺寸、形象、发现

2023-09-10 19:30:10 作者:‖埖颩,

我在动态使用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