如何创建简单的jQuery插件?

这个测试插件应该像这样工作:单击一个元素时,它会向下移动。 就那么简单。

jQuery.fn.moveDown = function(howMuch){ $(this).css("border", "1px solid black"); $(this).click(function(){ $(this).css("position", "relative"); $(this).animate({top: '+='+howMuch}); }); } 

问题是,当单击一个元素时,它不仅会移动被点击的元素,还会移动插件所应用的所有其他元素。

这是什么解决方案?

对于插件创作尝试这种方式,更加可靠:

编辑: 这是工作jsFiddle的例子。


插入:

 (function($){ $.fn.extend({ YourPluginName: function(options) { var defaults = { howMuch:'600', animation: '',//users can set/change these values speed: 444, etc: '' } }; options = $.extend(defaults, options); return this.each(function() { var $this = $(this); var button = $('a', $this);// this represents all the 'a' selectors; // inside user's plugin definition. button.click(function() { $this.animate({'top':options.howMuch});//calls options howMuch value }); }); })(jQuery); 

用户文件:

 $(function() { $('#plugin').YourPluginName({ howMuch:'1000' //you can give chance users to set their options for plugins }); }); 
1 2 3

在这里,我想建议使用参数创建简单插件的步骤。

JS

 (function($) { $.fn.myFirstPlugin = function( options ) { // Default params var params = $.extend({ text : 'Default Title', fontsize : 10, }, options); return $(this).text(params.text); } }(jQuery)); 

在这里,我们添加了名为params默认对象,并使用extend函数设置选项的默认值。 因此,如果我们传递空白参数,那么它将设置默认值,否则它将设置。

HTML

 $('.cls-title').myFirstPlugin({ text : 'Argument Title' }); 

阅读更多: 如何创建JQuery插件

原始答案 在这里,我想建议使用参数创建简单插件的步骤