I'm trying to get write a simple jQuery plugin, I've come to a stumbling block though in that I'm not sure how to access variables on the plugin from within a method for that plugin.
(function($) {
$.fn.testPlugin = function() {
var testVar = "Hello World";
alert(testVar);
$.fn.testPlugin.testMethod();
};
$.fn.testPlugin.testMethod = function() {
alert($.fn.testPlugin.testVar);
};
}(jQuery));
$("body").testPlugin();
This code first alerts "Hello World" then "undefined" (so attempting to access it from within the method returns an empty variable), is there any way to access testVar from within the testMethod? Is this not possible? Am I going about this in the wrong way?
You are creating a local variable inside your first method. That makes it's scope restricted to the method itself.
Instead, you should actually create that variable with reference to the plugin like this :
$.fn.testPlugin.testVar = "Hello World";
Your updated plunker goes here : http://jsfiddle.net/5zt9ps20/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句