开发者

Simple jquery plugin

I want to build a simple jQuery plugin, but I don't know how to start, I read a few articles and even tried to learn code of a few popular plugins, but it draw me even deeper into confusion.

Show me please a starter template. Let's say for the sake of example I should get something, that I can call开发者_运维知识库 like that:

 $("a").myMessagePlugin();

Now, everytime somebody clicks a link it should just popup an alert and show that link.

Thank you


Whenever you write a jQuery plugin make sure you return the jQuery object because it will help in chaining the jQuery methods.

$.fn.myMessagePlugin = function(options) {
    return this.each(function(){
        //plugin logic here
        $(this).click( function() { 
           alert(this.href);
        });
    });
}


The other answers are mostly correct, but if you want to use the dollar sign, wrap it in an anonymous function and pass the jQuery object. Otherwise, you run the risk of conflicting with other libraries.

(function($) {
    $.fn.myMessagePlugin = function(options) {
        return this.click( function() { //jQuery object, to be returned
            alert(this.href); //html element
        });
    }
})(jQuery);


it is recomended you specify undefined as well (I'm using previous example as base, thanks)

Also a good practice is to define defaults for the options and extend them using $.extend

(function($, undefined) {
    $.fn.myPlugin= function(options) {
        var opts = $.extend($.fn.myPlugin.defaults, options);

        return this.click( function() { //jQuery object, to be returned
            alert(this.href); //html element
        });
    }

    $.fn.myPlugin.defaults =  {
       "option1": 1,
       "option2": 2
    }
})(jQuery);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜