简体   繁体   English

从jQuery插件中调用函数

[英]Calling function from within jquery plugin

I'm writing my first jquery plugin and wondered what the correct/best practice way of referencing another function from within a plugin was? 我正在编写我的第一个jquery插件,想知道从插件中引用另一个函数的正确/最佳实践方法是什么? Is there a better way to define bar in my plugin script. 有没有更好的方法来在我的插件脚本中定义bar Should it be within function($) ? 它应该在function($)吗? I'd also like it to be available to other plugins within the script. 我也希望脚本中的其他插件可以使用它。

function bar() {
    return 'is this best paractice?';
}

(function($) {
    $.fn.foo = function() { 
        alert(bar());
    };
}(jQuery));

Why doesn't something like this work: 为什么这样的东西不起作用:

(function($) {
    $.fn.bar = function() {
        return 'is this best paractice?';
    };
}(jQuery));

(function($) {
    $.fn.foo = function() { 
        alert(bar());
    };
}(jQuery));

Thanks 谢谢

Functions added to $.fn will be used as jQuery plugins. 添加到$ .fn中的函数将用作jQuery插件。 If you just want to provide a global function from your plugin you add it to $ directly (eg $.bar = function() ...). 如果只想从插件中提供全局函数,则将其直接添加到$中(例如$ .bar = function()...)。

If you just want use the function internally for your plugin put it within function($). 如果只想在插件内部使用该函数,则将其放在function($)中。 That way you make it available only in that scope (the anonymous function) and not everywhere. 这样,您就只能在该范围(匿名函数)中使用它,而不能在任何地方使用它。

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

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