javascript 如何将参数传递给 jQuery 插件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17130150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:10:18  来源:igfitidea点击:

How to pass parameter to a jQuery plugin

javascriptjquery

提问by eepp

I have a question which at the first glance might seem to be stupid. I got problem figuring it out and whenever I use it, nothing really happens. I have a plugin in jQuery written by myself which is like this:

我有一个乍一看似乎很愚蠢的问题。我在弄清楚它时遇到了问题,每当我使用它时,什么都没有发生。我有一个自己编写的jQuery插件,如下所示:

(function(){
$.fn.myPlugin = function(options){
var options = $.extend({
firstParameter : null;
}
// the rest of the plugin
})(jQuery)

But when I call it from an HTML file, like this: ("#object").myPlugin(2);, it fails to work (note the parameter that I have passed). But if I skip the argument and call it like this: ("#object").myPlugin();, it all works. What is the problem?

但是当我从 HTML 文件调用它时,像这样: ("#object").myPlugin(2);,它无法工作(注意我传递的参数)。但是,如果我跳过参数并像这样调用它:("#object").myPlugin();,一切都有效。问题是什么?

Thanks in advance

提前致谢

回答by eepp

You want this:

你要这个:

(function($) {
    $.fn.extend({
        myPlugin: function(options) {
            var defaults = {
                something: 23,
                otherThing: 'hello'
            };

            options = $.extend(defaults, options);

            console.log(options.something);
            console.log(options.otherThing);
        }
    });
})(jQuery);

Now this should work to override the somethingoption (don't forget to pass an object):

现在这应该可以覆盖something选项(不要忘记传递一个对象):

$('#object').myPlugin({something: 17});

回答by simpletron

You define a function with no parameter function() {} then you pass the jQuery to it. It may be the cause of problem.

您定义了一个没有参数 function() {} 的函数,然后将 jQuery 传递给它。这可能是问题的原因。

(function(){
  // nothing is the $ here
  $.fn.myPlugin = function(options){
    var options = $.extend({
     firstParameter : null;
    }
  // the rest of the plugin
 })(jQuery)

You should change to

你应该改为

(function($) {})(jQuery) 

and I think it will work. Hope this help

我认为它会起作用。希望这有帮助