jQuery 提供兩個擴充用的方法:jQuery.extend(object) 擴充 jQuery 類本身,為類添加靜態方法;jQuery.fn.extend(object) 則是給 jQuery 物件(也就是每個選到的元素)添加方法。兩者的差別,在寫插件時至關重要。
<html>
<head><title></title></head>
<body>
<h3 class="ye">new soul</h3>
<h3 class="ye">new soul</h3>
<h3 class="ye">new soul</h3>
<h3 class="ye">new soul</h3>
<script type="text/javascript" src="jquery.2.0.3.js"></script>
<script type="text/javascript">
jQuery.fn.myPlugin = function(options) {
$options = $.extend( {
html: "no messages",
css: {
"color": "red",
"font-size":"14px"
}
},
options);
return $(this).css({
"color": $options.css.color,
}).html($options.html);
}
$('.ye').myPlugin({html:"So easy,yes?",css:{"color":"green","font-size":"20px"}});
</script>
</body>
</html>
這裡就出现了 $.extend() 最常見的用法:用傳入值覆蓋預設值。先宣告一份 defaults,再把使用者的 options 疊上去,就得到一份完整的設定物件。
// 用法: jQuery.extend(obj1, obj2, obj3, ...)
var Css1 = {size: "10px", style: "oblique"}
var Css2 = {size: "12px", style: "oblique", weight: "bolder"}
$.jQuery.extend(Css1, Css2)
// 結果:Css1 的 size 被覆蓋,並繼承了 Css2 的 weight
// Css1 = {size: "12px", style: "oblique", weight: "bolder"}
行為類似陣列的合併,但操作對象是物件:後者同名的屬性會蓋掉前者,同時把前者沒有的屬性併進來。注意它會直接修改第一個參數,若不希望動到原物件,傳入空物件當第一個參數即可。
jQuery.extend(
{ name: "John", location: { city: "Boston" } },
{ last: "Resig", location: { state: "MA" } }
);
// 結果:
// => { name: "John", last: "Resig", location: { state: "MA" } }
// 注意 city 整個被覆蓋掉了
// 新的更深入的 .extend()
jQuery.extend( true,
{ name: "John", location: { city: "Boston" } },
{ last: "Resig", location: { state: "MA" } }
);
// 結果
// => { name: "John", last: "Resig",
// location: { city: "Boston", state: "MA" } }
第一個參數傳 true 就開啟深度合併,這時 jQuery 會遞迴處理巢狀物件,把兩邊的子屬性都保留下來。設定物件裡有巢狀結構時,這個開關是必備的。
<html>
<head><title></title></head>
<body>
<script type="text/javascript" src="jquery.2.0.3.js"></script>
<script type="text/javascript">
$.extend({
add: function(a,b){return a+b;},
minus: function(a,b){return a-b},
multiply: function(a,b){return a*b;},
divide: function(a,b){return Math.floor(a/b);}
});
var sum = $.add(3,5) + $.minus(3,5) + $.multiply(3,5) + $.divide(5,7);
console.log(sum);
</script>
</body>
</html>
用 $.extend() 掛上去的方法屬於 jQuery 這個「類」本身,呼叫形式是 $.add();而用 $.fn.extend() 掛上去的則屬於每個選到的元素,呼叫形式是 $("div").myPlugin()。寫工具函式選前者,寫 DOM 操作插件選後者。