開發本身須要的jQuery插件,看個示例說明
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title> new document </title>
<meta name="generator" content="editplus">
<meta name="author" content="">
<meta name="keywords" content="">
<meta name="description" content="">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
/*
jQuery插件的開發包括兩種:
一種是類級別的插件開發,即給jQuery添加新的全局函數,至關於給jQuery類自己添加方法。jQuery的全局函數就是屬於jQuery命名空間的函數,
另外一種是對象級別的插件開發,即給jQuery對象添加方法。下面就兩種函數的開發作詳細的說明。
一、類級別的插件開發
類級別的插件開發最直接的理解就是給jQuery類添加類方法,能夠理解爲添加靜態方法。典型的例子就是$.AJAX()這個函數,將函數定義於jQuery的命名空間中。關於類級別的插件開發能夠採用以下幾種形式進行擴展:
*/
//1.1定義一個全局函數
jQuery.foo = function() {
alert('添加一個新的全局函數');
}
//定義多個全局函數
jQuery.bar = function() {
alert('再增長一個全局函數');
}
//1.2使用extend定義全局函數
jQuery.extend({
foo1:function() {
alert('extend 定義全局函數1');
},
bar1:function() {
alert('extend 定義全局函數2');
}
});
//1.3 使用命名空間定義函數
jQuery.plugin = {
foo2:function() {
alert('使用namespace定義函數');
}
}
$(function(){
$.foo();
$.bar();
$.foo1();
$.bar1();
$.plugin.foo2();
});
/*
二、對象級別的插件開發
對象級別的插件開發須要以下的兩種形式:
*/
//形式一
(function($){
$.fn.extend({
foo3:function() {
alert('對象級別插件extend方式1');
},
bar3:function() {
alert('對象級別插件extend方式2');
}
})
})(jQuery);
//形式二
(function($){
$.fn.foo4 = function() {
alert('對象級別插件fn方式');
}
})(jQuery);
//接收參數來控制插件的行爲
(function($){
$.fn.bar4 = function(options) {
var defaults = {aaa:'1',bbb:'2'};
var opts = $.extend(defaults, options);
alert('參數值:aaa:'+opts.aaa+';bbb:'+opts.bbb);
}
})(jQuery);
//提供公有方法訪問插件的配置項值
(function($){
$.fn.foo5 = function(options) {
var opts = $.extend({}, $.fn.foo5.defaults, options);
alert('參數值:aaa:'+opts.aaa+';bbb:'+opts.bbb);
}
$.fn.foo5.defaults = {aaa:'1',bbb:'2'};
})(jQuery);
//提供公有方法來訪問插件中其餘的方法
(function($){
$.fn.bar5 = function(options) {
$.fn.bar5.alert(options);
}
$.fn.bar5.alert = function(params) {
alert(params);
}
})(jQuery);
$(function(){
$('#test').foo3();
$('#test').bar3();
$('#test').foo4();
$('#test').bar4();
$('#test').bar4({aaa:'3'});
$('#test').bar4({aaa:'3',bbb:'4'});
$('#test').foo5();
$('#test').foo5({aaa:'5',bbb:'6'});
$('#test').bar5('aaaa');
});
</script>
</head>
<body>
<div id="test"></div>
</body>
</html> javascript