How to pass parameter to jQuery plugin

I have a question that might seem silly at first glance. It’s hard for me to figure it out, and whenever I use it, nothing happens. I have a jQuery plugin written by me that looks like this:

(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, for example: ("#object").myPlugin(2); It does not work (pay attention to the parameter that I passed). But if I skip the argument and name it like this: ("#object").myPlugin(); it all works. What is the problem?

Thank you in advance

+4
source share
2 answers

Do you want to:

 (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 something parameter (remember to pass the object ):

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

You define a function without a parameter function () {}, then pass jQuery to it. This may be causing the problem.

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

You have to switch to

 (function($) {})(jQuery) 

and I think it will work. We hope for this help.

0
source

Source: https://habr.com/ru/post/1486455/


All Articles