1:插件写法
(1)对HTML标记或页面元素进行扩展,使用这种插件的扩展方式,在使用此插件时,需要首先引用经过JQuery包装的页面元素,如:$("#tableId").Method()。
(function($){
//扩展这个方法到jquery
$.fn.extend({
//插件名称
one:function(options){//参数
var defaults = {//默认参数
animatePadding:"30px",
defaultPadding:"0px",
hoverColor:"red"
}
options = $.extend(defaults,options);//合并参数
return this.each(function(){//遍历匹配的每个对象
//...要执行的js
var me = $("li",this);
$(me).hover(function(){
$(this).css("color",defaults.hoverColor);
$(this).animate({"paddingLeft":defaults.animatePadding},{queue:false,duration:200});
},function(){
$(this).css("color","");
$(this).animate({"paddingLeft":defaults.defaultPadding},{queue:false,duration:200});
})
})
}
})
})(jQuery)
执行
$("#catagory").one({"animatePadding":"50px","hoverColor":"blue"});
<!--或-->
$("#catagory").one();
(2)和(1)一样,只是写法有点区别
(function($){
//插件名称
$.fn.otherone=function(options){//参数
var defaults = {//默认参数
animatePadding:"50px",
defaultPadding:"0px",
hoverColor:"red"
};
options = $.extend(defaults,options);//合并参数
//...要执行的js
var me = $("li",this);
$(me).hover(function(){
$(this).css("color",defaults.hoverColor);
$(this).animate({"paddingLeft":defaults.animatePadding},{queue:false,duration:200});
},function(){
$(this).css("color","");
$(this).animate({"paddingLeft":defaults.defaultPadding},{queue:false,duration:200});
})
}
})(jQuery)
执行
$("#catagory").otherone({"animatePadding":"50px","hoverColor":"yellow"});
<!--或-->
$("#catagory").otherone();
(3)JQuery自身的扩展插件--顾名思义,这种插件是对JQuery自身的方法库进行扩展的。在使用的时候通过$.getCss()的方式直接使用。
$.extend({
getCss:function(target){
return $(target).css("color");
}
})
执行
$("#catagory li").click(function(){
alert($.getCss(this))
})
以上代码的html代码如下:
<ul id="catagory">
<li>jQuery</li>
<li>Asp.net</li>
<li>Sql Server</li>
<li>CSS</li>
</ul>
2:jquery中的$.data(key,value)
简单的理解就是用来存储对象的数据,是以键值对的形式存在的
$(document).ready(function(){
$("a").data("str","this is on $.data save data");//这种方法首先要有a元素,因为是用a元素来存储数据的,没有的话没地方存.
alert($("a").data("str"));
//或
var a = $("a");
$.data(a,"str","this is on other $.data save data");//这种方法页面中可以不用有a元素,因为它存到了变量a中,相当于划了一块区域放a,只是a代表的是$("a")
alert($.data(a,"str"));
//移除对象
$("a").removeData("str");
alert($("a").data("str"));//弹出undefined,被移除了
//或
$.removeData(a,"str");
alert($.data(a,"str"));//弹出undefined,被移除了
})
3:jquery bind(type,[exp],fn)
<head>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#category li").bind("click",{savedata:"li click"},function(e){
alert($(this).html()+e.data.savedata);
})
})
</script>
</head>
<body>
<ul id="category">
<li>jQuery</li>
<li>Asp.net</li>
<li>Sql Server</li>
<li>CSS</li>
</ul>
</body>