1. 程式人生 > >jQuery 插件開發

jQuery 插件開發

turn str ima 沒有 -1 通過 undefined img 頁面

jQuery 插件的實質, 就是給jQuery的原型prototype上增加方法
jQuery.prototype.syaHi = function(){
  console.log("hehe");
}

這樣 jQuery對象就可以調用方法: #(document).sayHi();

jQuery == $ and prototype == fn
jQuery.prototype == $.fn

$(function(){    
    // 比如 重寫下面的jQuery方法 改變jQuery對象的背景顏色 
    $("div").css("background", "red");
    
    $.fn.bgColor 
= function(color) { // this 指的jQuery對象, 將來誰調用bgColor方法, 隨就是this this.css("background", color); } // 使用自定的jQuery方法改變背景顏色 this == $("div"); $("div").bgColor("red"); });

那自定義的方法怎麽提供給其他人或其他頁面使用呢 ?
我們需要把自定義的方法寫在單獨的js文件中, 這樣 只要別的頁面引用了這個文件 就可以調用我們自定義的方法

創建 jQuery.bgColor.js

    $.fn.bgColor = function(color) {
        this.css("background", color);
    }

引用自定義js文件

<script src="jquery.js"></script>
<script src="jQuery.bgColor.js"> </script>

這樣 在頁面中就可以直接調用自定義方法了:
$(function(){
  // 使用自定的jQuery方法改變背景顏色
  $("div").bgColor("red");
});

但上面的自定方法有一個問題 通過自定的方法可以繼續使用jQuery的鏈式編程嗎
比如繼續調用jQuery方法:
$("div").bgColor("red").width(400);

技術分享

這是因為我們自定義方法沒有返回值, 所以默認返回值是undefined

 $.fn.bgColor = function(color) {
        this.css("background", color);
    }
所以完整的自定義方法應該是
    $.fn.bgColor = function(color) {
        this.css("background", color);
        return this;
    }

這樣就可以繼續使用鏈式編程了 這也是jQuery鏈式編程的原理 return this

jQuery 插件開發