Jquery - 从插件外部访问变量

时间:2011-03-16 19:52:00

标签: javascript jquery jquery-plugins

我有一个简单的插件如下:

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

我希望能够通过以下方式更改/访问插件外部的变量myvar:

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

3 个答案:

答案 0 :(得分:2)

您还可以创建方法来访问插件内的变量:

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

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

}

然后你就可以这样称呼它。

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

答案 1 :(得分:1)

此解决方案不是直截了当的,而是遵循jquery插件指南。

(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");

});

答案 2 :(得分:0)

您是否考虑将其作为属性进行访问?类似的东西:


$.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');
    }
});

}

并设置如下:

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');
    }
});