JQuery Plugin 1 - Simple Plugin

时间:2023-03-09 01:54:52
JQuery Plugin 1 - Simple Plugin

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');