jQuery插件開發
jQuery開發分為兩種:
1 類級別
類級別你可以理解為拓展jquery類,最明顯的例子是$.ajax(...),相當於靜態方法。
開發擴展其方法時使用$.extend方法,即jQuery.extend(object);
2 對象級別
對象級別則可以理解為基於對象的拓展,如$("#table").changeColor(...); 這裏這個changeColor呢,就是基於對象的拓展了。
開發擴展其方法時使用$.fn.extend方法,即jQuery.fn.extend(object);
下麵有兩個例子:
1 類級別:
showMsg.js
$.extend({
showMsg:function(name)
{
alert("歡迎您"+name);
}
});
testMsg.html
<head>
<title>xy插件使用</title>
<script type="text/javascript" language="javascript" src="js/jquery-1.4.1.min.js"></script>
<script type="text/javascript" language="javascript" src="js/showMsg.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.showMsg("xy");
});
</script>
</head>
<body></body>
2 對象級別
xuyueTableUI.js
/*
* xytableUI 0.1
* Copyright (c) 2009 xy https://blog.csdn.net/woshixuye
* Date: 2012-02-18
* 使用tableUI可以方便地將表格提示使用體驗。先提供的功能有奇偶行顏色交替,鼠標移上高亮顯示
*/
(function($){
$.fn.extend({
xyTableUI:function(options){
var defaults = {
evenRowClass:"evenRow",
oddRowClass:"oddRow",
mouseoverRowClass:"mouseoverRow"
}
var options = $.extend(defaults,options);
return this.each(function(){
var thisTable=$(this);
// 添加奇偶行顏色
thisTable.find("tr:even").addClass(options.evenRowClass);
thisTable.find("tr:odd").addClass(options.oddRowClass);
// 添加活動行顏色
thisTable.find("tr").mouseover(function(){
$(this).addClass(options.mouseoverRowClass);
})
thisTable.find("tr").bind("mouseout",function(){
$(this).removeClass(options.mouseoverRowClass);
});
});
}
});
})(jQuery);
/*
(function($){
$.fn.extend({
yourname:function(options){
var defaults = {
//各種屬性、參數
}
//合並多個對象為一個。如果你在調用的時候寫了新的參數,就用你新的參數。
//如果沒有寫,就用默認的參數。
var options = $.extend(defaults,options);
return this.each(function(){
//插件實現代碼
});
}
});
})(jQuery);
*/
xyTableUI.css
/*odd行樣式*/
.oddRow
{
background-color: lightblue;
}
/*even行樣式*/
.evenRow {
background-color: yellow;
}
/*鼠標劃過樣式*/
.mouseoverRow
{
background-color: red;
}
/*測試帶參數使用時樣式*/
.testRow
{
background-color: pink;
}
table
{
width:50%;
border:1px solid black;
border-collapse:collapse;
}
td
{
border:1px solid black;
}
html
<head>
<title>xy表格Jquery插件使用</title>
<link rel="stylesheet" type="text/css" href="css/xyTableUI.css" />
<script type="text/javascript" language="javascript" src="scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" language="javascript" src="scripts/xuyueTableUI.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// 不帶參數使用插件
//$(".xyTableUI").xyTableUI();
// 帶參數使用插件
$(".xyTableUI").xyTableUI({mouseoverRowClass:"testRow"});
});
</script>
</head>
<body>
<table >
<tr>
<td align="right">
aaa
</td>
...............................................................
</table>
</body>
參考博客:https://developer.51cto.com/art/201108/286391.htm
https://www.jb51.net/article/22849.htm
最後更新:2017-04-02 22:16:20