简体   繁体   中英

Jquery - Access variable from outside the plugin

I got a simple plugin as below:

$.fn.ajaxSubmit = function(options){
    var submisable = true;
}

I want to able to change/access the variable myvar from outside the plugin, by doing something like below:

$(function(){
    $('form').ajaxSubmit();
    $('div').click(function(){
        submisable =false;
    });
});

You can also create methods to access the variables that are inside a plug in:

$.fn.ajaxSubmit = function(options){
    var submisable = true;

    $.fn.ajaxSubmit.setSubmissable = function(val){
       submisable = val;
    }

}

Then you can call it like this.

$('form').ajaxSubmit();
$('form').ajaxSubmit.setSubmissable(false);

This solution is not straight forward, but follows the jquery plugin guidelines.

(function($) {
    var myVar = "Hi";
    var methods = {
        init: function(option) {
            return this.each(function() {
                $(this).data("test", myVar);
            });
        },
        showMessage: function() {
            return this.each(function() {
                alert($(this).data("test"));
            });
        },
        setVar: function(msg) {

            return this.each(function() {
                $(this).data("test", msg);
            });
        },
        doSomething: function() { 
            //perform your action here
        }
    }

    $.fn.Test = function(method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.Test');
        }
    };
})(jQuery);

$("form").Test("init");
$("#getCol").click(function() {
    $("form").Test("setVar", "Hello World").Test("showMessage");

});

Are you thinking to access them as properties? Something like:


$.fn.ajaxSubmit = function(options) {
    var defaults = {},
    o = $.extend({}, defaults, options);
    var _myvar = 'blue'

this.myvar = new function(){
  return _myvar;
}
this.setmyvar = function(_input){
  _myvar = _input
}

return this.each(function() {           

    if (_myvar == 'blue') {
        alert('hi');
    }
    if (_myvar == 'red') {
        alert('bye');
    }
});

}

And set like:

this.setmyvar('red');

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