JQuery Plugin 1 - Simple Plugin

原文链接:http://www.cnblogs.com/davidgu/p/3331537.html

1. How do you write a plugin in jQuery?

You can extend the existing jQuery object by writing either methods or functions.

1) Writing a custom jQuery method

jQuery methods are defined by extending the jQuery.fn object with your method name.

$.fn.extend({
    //Only Test
    MasterTest: {
        alertTest: function () {
            alert('Welcome Master HaKu!');
        }
    }
});

call the method

$(document).ready(function () {
        $('#btnAlert').click(function () {
            $.fn.MasterTest.alertTest();
        });
    });


eg:

/*
    JQuery Plugin - custom jQuery method
*/

$.fn.appendHtml = function (destId, appendId) {
    $(destId).append('<div>Add Text: ' + $(appendId).html() + '</div>');
};

call the method

$.fn.appendHtml('#result', '#myText');


2) Writing a custom jQuery function

 

eg:

/*
    JQuery Plugin - custom jQuery function
*/

$.appendHtml = function(destId, appendId) {
    $(destId).append('<div>Append: ' + $(appendId).html() + '</div>');
};


call the function

$.appendHtml('#result', '#myText');

 

 

 

 

 

 

转载于:https://www.cnblogs.com/davidgu/p/3331537.html

展开阅读全文
博主设置当前文章不允许评论。

没有更多推荐了,返回首页