2011-03-16 50 views
1

我有如下一个简单的插件:jQuery的 - 从插件外部访问变量

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

我希望能够改变从插件外/访问变量MYVAR,通过执行类似如下:

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

回答

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

}); 
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.setmyvar('red');
+0

我已更新问题 – 2011-03-17 03:15:04

2

您还可以创建方法来访问是塞在里面的变量:

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

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

} 

然后,你可以这样调用。

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