Jquery 图像对象

Jquery Image object

本文关键字:对象 图像 Jquery      更新时间:2023-09-26

我试图理解JQuery的这一部分。

$.fn.imageCrop = function(customOptions) {
        //Iterate over each object
        this.each(function() {
            var currentObject = this,
                image = new Image();
            // And attach imageCrop when the object is loaded
            image.onload = function() {
                $.imageCrop(currentObject, customOptions);
            };
            // Reset the src because cached images don't fire load sometimes
            image.src = currentObject.src;
        });
        // Unless the plug-in is returning an intrinsic value, always have the
        // function return the 'this' keyword to maintain chainability
        return this;
    };

我无法理解的是,创建了一个新的,因此为空的 Image 对象,然后将一个 onload 方法添加到图像中,然后手动重置 image.src,以防它不触发重新加载。但是为什么它会触发重新加载呢?它只是一个空的图像对象,与任何东西都没有关系。是否以某种方式自动链接到当前对象?

这是我注释的代码,看看是否有帮助。必须将 src 设置为等待事件

    //this is a jquery plugin,
//jquery plugins start this way 
//so you could select $('img').imageCrop();
$.fn.imageCrop = function(customOptions) {
    //Iterate over each object
    this.each(function() {
        //keeps the current iterated object in a variable
        //current image will be kept in this var untill the next loop
        var currentObject = this,
        //creates a new Image object    
        image = new Image();
        // And attach imageCrop when the object is loaded
        //correct
        image.onload = function() {
            $.imageCrop(currentObject, customOptions);
        };
        //sets the src to wait for the onload event up here ^
        image.src = currentObject.src;
    });
    // Unless the plug-in is returning an intrinsic value, always have the
    // function return the 'this' keyword to maintain chainability
    return this;
};