简体   繁体   中英

How to get variable defined inside of jQuery custom plugin

I am working on a custom jQuery plugin. I need to access the options passed in the first function within the second function.

The problem is if I declare settings outside of these functions, it gets mixed up when I have multiple instances of this plugin initialized on the same page.

(function($) {

    $.fn.MyCombobox = function(options) {
        var settings = $.extend({
            selector: '.myselector'
        }, options);
    };

    $.fn.MyCombobox.clear = function() {
        $(settings.selector).find('input').val('');
    };

}(jQuery));

One approach would be to set .data() at .MyCombobox

 (function($) { $.fn.MyCombobox = function(options) { var settings = $.extend({ selector: '.myselector' }, options); this.data("options", settings); return this }; $.fn.clear = function() { console.log(this.data("options") || {/* default settings here */}) }; }(jQuery)); $("div").MyCombobox().clear(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div> 

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