简体   繁体   English

如何从方法中访问jQuery插件变量?

[英]How do I access a jQuery plugin variable from within method?

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. 我正在尝试编写一个简单的jQuery插件,虽然我不确定如何从该插件的方法中访问插件上的变量,但我遇到了绊脚石。

(function($) {
    $.fn.testPlugin = function() {
        var testVar = "Hello World";
        alert(testVar);
        $.fn.testPlugin.testMethod();
    };

    $.fn.testPlugin.testMethod = function() {
        alert($.fn.testPlugin.testVar);
    };
}(jQuery));

$("body").testPlugin();

FIDDLE HERE 骗子在这里

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? 此代码首先警告“Hello World”然后“undefined”(因此尝试从方法中访问它返回一个空变量),有没有办法从testMethod中访问testVar? Is this not possible? 这不可能吗? Am I going about this in the wrong way? 我是以错误的方式解决这个问题吗?

You can put variable in the outer scope - scope of your self invoking function. 您可以将变量放在外部作用域中 - 自调用函数的作用域。

(function($) {
    var testVar;
    $.fn.testPlugin = function() {
        testVar = "Hello World";
        alert(testVar);
        $.fn.testPlugin.testMethod();
    };

    $.fn.testPlugin.testMethod = function() {
        alert(testVar);
    };
}(jQuery));

$("body").testPlugin();

This could be more desirable approach if for example you do not want your variable to be accessible by any other code except your plugin. 如果您不希望除插件之外的任何其他代码都可以访问您的变量,那么这可能是更理想的方法。 Fiddle: http://jsfiddle.net/79sg8es1/ . 小提琴: http//jsfiddle.net/79sg8es1/

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/ 你更新的plunker在这里: http//jsfiddle.net/5zt9ps20/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM