开发者

How to write my first jQuery Plugin?

I'm now writing my first jQuery Plugin and i found this blog post about 'Building you first jQuery plugin' but in the first step they give 2 ways of writing the plugin: The First One:


$.fn.yourPlugin = function(options) {

   return this.each(function() {

   });
};


And The Second One:


(function($){
 $.fn.yourPlugin = function() {

    return开发者_运维知识库 this.each(function() {

    });
 };
})(jQuery);


Because They say there could be some problems with the $ like conflicts with another libraries....

So I'd like to know what's the best practice here.


Absolutely in every case the second one. Do not use the first one unless you are the only one that is going to be using the plugin and can insure that the $ variable will always point to jQuery.


Best practice is definitely the second option. jQuery has a great article on plugin authoring with a number of additional best practices. There's also a starting "template" that takes your second option a bit further.


Use the second one. It will allow you to use $ inside that anonymous function without having to worry about clashes with other frameworks which use the $.


Basically jQuery is a JS framework (better to say a JS library). Plugins are the way you extend core functionalities with new one.

Here is an easy to read tutorial with downloadable sample code which describes all parts of typical plugin code: how to make jquery plugin hello world

Reading it you can understand the idea behind plugins and as it is a hello world so it start from very basic steps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜