jQuery爲開發插件提拱了兩個方法,分別是:
jQuery.extend(object)
jQuery.fn.extend(object)
jQuery.extend(object); 爲擴展jQuery類本身.爲類添加新的方法。可以理解爲添加靜態方法
示例如下,返回兩個數種較大的一個
$.extend({
Max:function(a,b){
if(a>b){
return a;
}else{
return b;
}
}
});
調用方法:
var max=$.Max(10,100);//返回兩個數種較大的一個
jQuery.fn.extend(object);給jQuery對象添加方法,對jQuery.prototype進行擴展,就是爲jQuery類添加“成員函數”。jQuery類的實例可以使用這個“成員函數”。
查看fn的jQuery代碼如下:
jQuery.fn=jQuery.prototype={
init:function(select,context){}
};
發現jQuery.fn = jQuery.prototype,是對其提供擴展方法,
下面使用jQuery.fn開發一個小插件,但文本框獲取焦點以後清空文本框的內容
jQuery.fn.extend({
cleartext:function(){
$(this).focus(function(){
$(this).val("");
});
}
});
調用方法如下:
$(document).ready(function(){
$("input[type='text']").cleartext();
});
<html>
<head>
<title></title>
</head>
<body>
<input type="text" value="input username" />
</body>
</html>