Writing Your Own jQuery Plugins

时间:2022-08-08 23:13:39

Setting Up

 <script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery.hello-world.js"></script>

The jQuery Plugin Structure

 (function($) {

     $.fn.helloWorld = function() {

         // Future home of "Hello, World!"

     }

 }(jQuery));

Making Our Plugin Do Something

 (function($) {

     $.fn.helloWorld = function() {

         this.each( function() {
$(this).text("Hello, World!");
}); } }(jQuery));

Invoke the plugin

 <script>
$(document).ready( function() {
$('h2').helloWorld();
});
</script>

Return the results of the plugin(necessary)

 (function($) {

     $.fn.helloWorld = function() {

         return this.each( function() {
$(this).text("Hello, World!");
}); } }(jQuery));

But Wait, There’s More!

 (function($) {

     $.fn.helloWorld = function( customText ) {

         return this.each( function() {
$(this).text( customText );
}); } }(jQuery));

Invoke the plugin

 <script>
$(document).ready( function() {
$('h2').helloWorld('¡Hola, mundo!');
});
</script>

Complete Customization

 (function($){
//
$.fn.helloWorld = function(options){ var settings = $.extend({
text: "hello girl!",
fontSize: null,
color: null,
},options); return this.each(function(){
$(this).text(settings.text);
if(settings.fontSize != null){
$(this).css("font-size",settings.fontSize);
}
if(settings.color != null){
$(this).css("color",settings.color);
}
}); } }(jQuery));

Use a “complete” variable to perform an action when our plugin completes its action.

 (function($){
//
$.fn.helloWorld = function(options){ var settings = $.extend({
text: "hello girl!",
fontSize: null,
color: null,
complete: function(){ alert("Done!");}
},options); return this.each(function(){
$(this).text(settings.text);
if(settings.fontSize != null){
$(this).css("font-size",settings.fontSize);
}
if(settings.color != null){
$(this).css("color",settings.color);
}
if($.isFunction(settings.complete)){
settings.complete.call(this);
} }); } }(jQuery));

On the invocation side, our code becomes:

 $('h2').helloWorld({
text : 'Salut, le monde!',
color : '#005dff',
fontStyle : 'italic',
complete : function() { alert( 'Done!' ) }
});

原文地址:Writing Your Own jQuery Plugins

jQuery 官网实例