建立簡單的jquery外掛程式
1、建立基本外掛程式的通用方法:
$.fn.greenify = function() { this.css( "color", "green" );}; $( "a" ).greenify();2、增加鏈式的調用:在上面的方法中增加this的返回
$.fn.greenify = function() { this.css( "color", "green" ); return this;} $( "a" ).greenify().addClass( "greenified" );3、保護js命名空間的乾淨 減少和其他的外掛程式的汙染, 避免和別的外掛程式的$的衝突,我們需要把我們的代碼放在一個立即調用的函數運算式內
然後傳遞jQuery,參數命名為$
(function ( $ ) { $.fn.greenify = function() { this.css( "color", "green" ); return this; }; }( jQuery ));另外,立即調用函數的主要目的是允許我們使用我們的私人變數,可以把值儲存在一個變數中
這樣就可以在立即調用函數中定義私人變數而不汙染公用環境
(function ( $ ) { var shade = "#556b2f"; $.fn.greenify = function() { this.css( "color", shade ); return this; }; }( jQuery ));儘可能的定義在一個方法內
(function( $ ) { $.fn.openPopup = function() { // Open popup code. }; $.fn.closePopup = function() { // Close popup code. }; }( jQuery ));
應該更改成:
(function( $ ) { $.fn.popup = function( action ) { if ( action === "open") { // Open popup code. } if ( action === "close" ) { // Close popup code. } }; }( jQuery ));
4、如果擷取的是一個dom集合,想操作其中的合格元素使用.each()的方法迴圈這個dom集合,返回的操作修改後的元素集,以供繼續調用方法
$.fn.myNewPlugin = function() {
return this.each(function() { // Do something to each element here. }); };
5、擴充參數:使用自訂的參數 覆蓋預設的參數 $.extend(settings,options);
function ( $ ) { $.fn.greenify = function( options ) { // This is the easiest way to have default options. var settings = $.extend({ // These are the defaults. color: "#556b2f", backgroundColor: "white" }, options ); // Greenify the collection based on the settings variable. return this.css({ color: settings.color, backgroundColor: settings.backgroundColor }); }; }( jQuery ));
$( "div" ).greenify({ color: "orange"});以下是以上的綜合樣本:
<script type="text/javascript" src="js/jquery-1.11.1.js"></script><script type="text/javascript">(function($){$.fn.greenify = function(options){var settings = $.extend({color:"green",backgroundColor:"black"},options);var that = this;return that.each(function(){$(this).css({color:settings.color,backgroundColor:settings.backgroundColor});});};})(jQuery);$(function(){$("a:lt(2)").greenify({color:"orange"}).html(111);});</script>This is my HTML page.
dianji dianji11 dianji221