本文用一個可實際操作的範例,說明 jQuery 外掛擴充的兩條路:物件層級($.fn)與類別層級($.fn.extend 或直接向 jQuery 掛函數)。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery 擴充外掛測試</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<style type="text/css">
.a{ background:#ccc; }
.b{ background:#555; }
</style>
<script type="text/javascript">
// 1. 物件層級的擴充:jQuery.fn 是 jQuery.prototype 的別名
// 注意:物件方法內的 this 指向一個 jQuery 物件,
// 但每次呼叫的 .each() 回呼裡,this 指向單一 DOM 元素
// (所以 each 內部要重新用 jQuery 包裝 this;return 之後才能再接 jQuery 的 each)
(function($){
$.fn.toggleClass = function(options){
return this.each(function(){
var opts = $.extend({}, $.fn.toggleClass.defaults, options);
var $element = $(this);
if ($element.hasClass(opts.class1)) {
$element.removeClass(opts.class1).addClass(opts.class2);
} else if ($element.hasClass(opts.class2)) {
$element.removeClass(opts.class2).addClass(opts.class1);
}
});
};
$.fn.toggleClass.defaults = { class1: "", class2: "" };
$.fn.setBorder = function(){
return this.each(function(){
$(this).css("border", "1px solid red");
});
};
})(jQuery);
$(function(){
var opts = { class1: "a", class2: "b" };
$("h1").click(function(){
$("h1").toggleClass(opts).setBorder();
});
});
// 2. 類別層級的擴充
// 1) 直接掛上去:為 jQuery 物件新增全域函數
jQuery.sum = function(array){
var total = 0;
jQuery.each(array, function(idx, num){
total += num;
});
return total;
};
// 2) 用 extend 一次掛多個
jQuery.extend({
fn1: function(){},
fn2: function(){}
});
</script>
</head>
<body>
<h1 id="h1" class="a">jQuery 擴充測試</h1>
</body>
</html>
幾個容易忽略的細節:
return this.each(...),才能維持 jQuery 的鏈式呼叫,上面的 toggleClass(opts).setBorder() 就是靠這個特性串起來的。$.fn.外掛名.defaults,再透過 $.extend 合併使用者傳入的參數,是 jQuery 外掛最標準的可配置寫法。(function($){ ... })(jQuery) 這個立即執行函數裡,可以確保 $ 在這個作用域內永遠屬於 jQuery,避免與其他函式庫衝突。jQuery.sum)則是掛在 jQuery 這個「類別」上,屬於工具函數,不需要先選到元素。