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