您的位置:首页 > Web前端 > JQuery

jquery插件

2019-06-08 22:39 1541 查看

jquery插件

插件机制简介

往jquery类库里面去扩展方法,这类方法就是jquery插件

json的三种格式

1 对象{sid:‘s01’,sname:‘zs’}

$(function(){
//json对象的字符串体现形式
var jsonObj1 = {
sid:"s001",
sname:"aa"
};
console.log(jsonObj1);
})


2 列表/数组[1,3,4,5]

$(function(){
//json数组的字符串体现形式
var json2 = [1,2,3,4];
console.log(json2);
})


3 混合模式 {id:3,hobby:[‘a’,‘b’,‘c’]}

$(function(){
//json混合模式的字符串体现形式
var json3 = {id:"01",hobby:["a","b","c","d"]};
console.log(json3);
})

$ .extend和$ .fn.extend

1 $ .extend:对象的扩展(或继承)

$ .extend(obj1,obj2)
$ .extend(obj1,obj2,obj3[,…])
$ .extend(obj1)/$.method=function(options){…};

$(function(){
//json对象的字符串体现形式
var json1 = {
sid:"s001",
sname:"aa"
};
var json2 = {
sid:"s002",
sname:"bb",
hobby:[1,2,3]
};
//$.extend是用来扩充jquery类属性或者方法所用的
var json = {};
//后面的对象扩充一个对象
//$.extend(json,json1);
//之前已经扩充的属性值会被后面的对象所覆盖,如果后面对象有新的属性,会继续扩充
$.extend(json,json1,json2);
console.log(json);
})

$(function(){
//扩充方法:
$.extend({
hello:function(){
alert("哈哈哈哈");
}
});

$.hello();
})

2 $ .fn.extend
$ .fn.extend(obj1)//$ .fn.method=function(options){…};

$(function(){
//$.fn.extend是用来扩充jquery实例属性或者方法所用的
$.fn.extend({
hello:function(){
alert("哈哈哈哈");
}
});
$("#h").hello();

})

jQuery插件的添加
其实就是给jQuery添加新的实例方法或类方法,然后将功能封闭在其中

jQuery插件开发实例

我们需要不同的表格有不同的样式:

弄一个 jquery.table.css,将所有css样式写在里面:

.fen {
background: #ff66ff;
}

.yellow {
background: #ffff66;
}

.red {
background: #ff3333;
}

.blue {
background: #9999ff;
}

.green {
background: #bbff99;
}
.hui {
background: #d6d6c2;
}

.over{
background:  olive;
}
.out{
background: aqua;
}
.head{
background: green;
}

弄一个 jquery.table.js,将方法写在里面:

$(function(){
var defaults = {
head : "head",
out : "out",
over: "over"
}
$.fn.extend({
//使用return的原因是让该实例方法支持链编程.好比stringbuffer
bgColor:function(option){
$.extend(defaults,option);
//这里的this指的是插件本身,可以看成一个jquery实例
return this.each(function(){
//给默认值
$("tr:eq(0)",this).addClass(defaults.head);
$("tr:gt(0)",this).addClass(defaults.out);

//添加动态效果
$("tr:gt(0)",this).hover(function(){
$(this).removeClass().addClass(defaults.over);
},function(){
$(this).removeClass().addClass(defaults.out);
});
})
}

})

})

通用的头部:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE>
<link href="${pageContext.request.contextPath }/jquery/table/css/jquery.table.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js" ></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/jquery/table/js/jquery.table.js"></script>

在jsp上加上这一行引用头部

<%@include file="/jsp/common/head.jsp" %>

然后在表格调用方法

$(function(){
$("table").bgColor({
head:"blue",
out:"yellow",
over:"hui"
});
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: