2012-01-07 90 views
1

我想编写一个函数,这样我可以像这样执行命令:编写你自己的Jquery函数?

$("#Button").glow(); 

我有什么重写,或者我怎么也得结构中的“发光”的功能,这样我可以称它为我在上面做的方式?

+2

阅读[文件](HTTP://文档.jquery.com/Plugins/Authoring) – 2012-01-07 16:07:26

回答

9

看看plugin authoring。阅读文档。做和尝试一些。例如像:

(function($) { 
    $.fn.glow = function(options) { 
     return this.each(function() {  
      // TODO: do something for each element that matched your selector 
     }); 
    }; 
})(jQuery); 
+4

-1的态度 – 2013-04-30 11:38:19

7
(function($) { 
    $.fn.glow = function() { 
     return this.each(function() { //<--optionally, parameters here 
      // your logic here 
      // `this` at this point refers to the DOM element 
     }); 
    } 
})(jQuery); //<-- Closure to allow using $ where $ is not jQuery any more 

return this.each(..)return能使链的jQuery插件,让你可以使用:

$("selector").glow().anothermethod(); 
//If return was omitted, the previous line would throw an error 
1
jQuery.fn.glow = function() { 
    //Do Stuff 
} 
2
(function($){ 

    $.fn.glow = function() { 

    //your selected element is 'this' 
    this. ...//do your magic 

    }; 
})(jQuery); 

然后你就可以使用它像这样:

$('#element').glow(); 

有关完整信息,请检查第是:http://docs.jquery.com/Plugins/Authoring

9

您必须声明一个jQuery之类的函数为:

jQuery.fn.myPlugin = function() { 

    // Do your awesome plugin stuff here 

}; 

后这里阅读

$("#Button").myPlugin(); 

http://docs.jquery.com/Plugins/Authoring