0

我试图理解这段 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 以防它不触发重新加载。但是为什么它会重新加载呢?它只是一个与任何东西无关的空图像对象。是否以某种方式自动链接到 currentObject?

4

1 回答 1

1

这是我的评论代码,看看它是否有帮助。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;
};
于 2013-09-26T10:30:49.140 回答