如何创建自定义JQuery函数以及如何使用它?

我正在搜索有关的信息 – “如何创建自定义(自己的)JQuery函数以及如何使用它”

我在谷歌搜索过,但我没有找到相关信息。

你能详细解释一下自定义function吗?

通过“自定义function”我假设你的意思是“插件”。 如果是这样的话, jQuery网站上有一个很好的教程 。 基本的想法是这样的:

(function($) { $.fn.myPlugin = function() { return this.each(function() { //Do stuff }); }; }(jQuery)); 

基本上,上面的代码做了一些事情。 首先,它捕获jQuery的值并将其传递给一个匿名函数,然后可以将其称为$ (这样,您的插件的用户恰好使用$ identifier的其他东西仍然可以使用它。)

然后它在$.fn上声明一个方法,它只是$.prototype的别名。 在该方法中, this指的是已调用插件的匹配元素集。 由于这是一个jQuery对象,并且可能包含多个元素,因此需要迭代该集合(这就是为什么each都在那里)。

return语句用于维护插件与其他jQuery方法的可链接性。 由于each返回一个jQuery实例,插件本身返回一个jQuery实例,显然可以在jQuery实例上调用其他jQuery方法。

正如gesutery所说,使用extend() 。 您可以将自己的属性和函数添加为值:

  $(function(){ $.extend({ propAsString: '', propAsNumber: 12345, propAsObject: {}, propAsFunction: function() { //your function code } }); $.propAsFunction(); //call your function }); 

你可以像这样使用它

  $(document).ready(function() { $('#button').click(function(){ $(this).myFunction(); }); $.fn.myFunction = function() { alert('test'); } }); 
 (function($){ $.fn.extend({ //plugin name - animatemenu animateMenu: function(options) { //Settings list and the default values var defaults = { animatePadding: 60, defaultPadding: 10, evenColor: '#ccc', oddColor: '#eee' }; var options = $.extend(defaults, options); return this.each(function() { var o =options; //Assign current element to variable, in this case is UL element var obj = $(this); //Get all LI in the UL var items = $("li", obj); //Change the color according to odd and even rows $("li:even", obj).css('background-color', o.evenColor); $("li:odd", obj).css('background-color', o.oddColor); //Attach mouseover and mouseout event to the LI items.mouseover(function() { $(this).animate({paddingLeft: o.animatePadding}, 300); }).mouseout(function() { $(this).animate({paddingLeft: o.defaultPadding}, 300); }); }); } }); })(jQuery); 

对于那些按照标题寻找“自定义function”的人来说,它很简单:

 if(window.$) window.$.customMethod = function() { * your code here * }; 

这将像$.ajax()那样工作

我希望像$.myfunction()一样调用我的自定义函数。 我在外部js文件中定义了这些函数,就像这样

 $.myfunction = function(){ //Your code here };