简体   繁体   中英

How To Create methods(functions) in jQuery Plugins

I want to create a plugin, which will be looking for a img file on PC, and after load this image file, the user can choose some methods to apply in this. For example, in a call plugin:

$('#test').myPlugin({
  legend: true
});

And my code for plugin upload a file is this:

    (function( $ ){
var handleFileSelect = function (evt) {
    var files = evt.target.files;
    for(var i = 0, f; f = files[i]; i++) {
        if (!f.type.match('image.*')) {
            continue;
        }
        var reader = new FileReader();
        reader.onload = (function(theFile) {
            return function(e) {
              // Render thumbnail.
              var span = document.createElement('span');
              span.innerHTML = ['<img class="responsive-img thumb" src="', e.target.result,
                                '" title="', escape(theFile.name), '"/>'].join('');
              document.getElementById('list').insertBefore(span, null);
            };
        })(f);
        reader.readAsDataURL(f);
    }
};
$.fn.upload = function(options) {
    var settings = $.extend( {}, options );
    return this.each(function() {
        document.getElementById('files').addEventListener('change', handleFileSelect, false);
    });
};
})( jQuery );

This code works fine on upload img , but I don´t have idea, how I can add methods in this plugin. Someone help me? Thanks!

how i can add methods in this plugin

The same way that you already do . Notice how you're adding a plugin function here:

$.fn.upload = function(options) {
    //...
}

So if you want to add a function by a different name, simply add a function by a different name:

$.fn.myPlugin = function(options) {
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM