在动态创建jQuery元素时是否触发了'ready'事件?

Rob*_*rve 7 jquery

我正试图在jQuery中实现类似照片轮播的东西.这个轮播可以使用图像源数组填充图像(我发出一个ajax请求,返回带有此数据的json),一旦填充,你可以调用几个方法,previous()和next()来移动转盘分别向后和向前.

问题是这个功能已经实现并且正常工作,但我无法解决调整大小过程的问题.为了避免图像超出容器的边界,我有一种方法可以根据需要创建和调整图像大小.

this.getImageResized = function(imageSrc) {

    var image = $('<img />', {src : imageSrc});

    // Container ratio
    var ratio = this.itemMaxWidth / this.itemMaxHeight;

    // Target image ratio is WIDER than container ratio
    if((image[0].width / image[0].height) > ratio) {
        if(image[0].width > this.itemMaxWidth) {
            image.css('width', this.itemMaxWidth + 'px');
            image.css('height', 'auto');
        }
    // HIGHER
    } else {
        if(image[0].height > this.itemMaxHeight) {
            image.css('width', 'auto');
            image.css('height', this.itemMaxHeight + 'px');
        }
    }

    // Embeds image into a wrapper with item's width and height
    var wrapper = $('<span style="display : block; float : left; width : ' + this.itemMaxWidth + 'px; height : ' + this.itemMaxHeight + 'px"></span>');

    image.appendTo(wrapper);

    return wrapper;
};
Run Code Online (Sandbox Code Playgroud)

测试这个功能,我发现有时,图像没有按预期调整大小.我已经使用firebug console.log()在jQuery元素创建之下记录图像[0] .width,发现有时值为0.

我不是jQuery的专家,但我想当发生这种情况时(值为0)是因为元素没有准备好.

当我询问其宽度和高度值时,如何确保元素已经加载?

这样的事情可能吗?

var image = $('<img />', {src : imageSrc}).ready(function() {
    // But image[0].width it's not available here!
});
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

Nic*_*ver 4

您想在这种情况下使用该load事件,如下所示:

var image = $('<img />', {src : imageSrc}).one('load', function() {
  // use this.width, etc
}).each(function() {
  if(this.complete) $(this).load();
});
Run Code Online (Sandbox Code Playgroud)

最后一位会触发load事件,以防它尚未被触发...从缓存加载图像时,在某些浏览器中不会发生这种情况,使用.one()一个仅触发一次并.complete检查它是否已加载。