jquery的extend和fn.extend的使用说明
jQuery为开发插件提拱了两个方法,分别是:
jQuery.extend(object); 为扩展jQuery类本身.为类添加新的方法。
jQuery.fn.extend(object);给jQuery对象添加方法。
fn 是什么东西呢。查看jQuery代码,就不难发现。
jQuery.fn = jQuery.prototype = {
init:function( selector, context ) {//....
//......
};
原来 jQuery.fn = jQuery.prototype.对prototype肯定不会陌生啦。
虽然javascript没有明确的类的概念,但是用类来理解它,会更方便。
jQuery便是一个封装得非常好的类,比如我们用 语句 $("#btn1") 会生成一个 jQuery类的实例。
jQuery.extend(object); 为jQuery类添加添加类方法,可以理解为添加静态方法。如:
$.extend({
add:function(a,b){returna+b;}
});
便为 jQuery 添加一个为 add 的 “静态方法”,之后便可以在引入jQuery 的地方,使用这个方法了,
$.add(3,4); //return 7
jQuery.fn.extend(object); 对jQuery.prototype进得扩展,就是为jQuery类添加“成员函数”。jQuery类的实例可以使用这个“成员函数”。
比如我们要开发一个插件,做一个特殊的编辑框,当它被点击时,便alert 当前编辑框里的内容。可以这么做:
$.fn.extend({
alertWhileClick:function(){
$(this).click(function(){
alert($(this).val());
});
}
});
$("#input1").alertWhileClick(); //页面上为:<input id="input1" type="text"/>
例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery的extend和fn.extend的使用</title>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
jQuery.fn.extend({
check: function() {
return this.each(function() {
this.checked = true;
});
},
uncheck: function() {
return this.each(function() {
this.checked = false;
});
}
});
// jquery 本身并不提供 jQuery.checkall() 这个方法,如果我们需要对jQuery本身提供的方法进行扩展,则我们就需要是用jQuery.fn.extend:
function checkall() {
// $("input[type=checkbox]").check();
$("input[name=a]").check();
}
function uncheckall() {
// $("input[type=checkbox]").uncheck();
$("input[name=a]").uncheck();
}
// 2.jQuery.extend 对jQuery对象的扩展,可以理解为静态方法,不需要实例jQuery就可以使用
jQuery.extend({
add: function(a, b) {
return a + b;
}
})
alert($.add(3, 4));
//把时间注册到id中,初始化
$(function() {
$("#Button1").click(function() {
$("#bgid").css("background-color", "red");
});
$("#Button2").click(function() {
$("#bgid").css("background-color", "white");
})
});
</script>
</head>
<body>
<form id="form1">
<div id="bgid" >
<input id="Button1" type="button" onclick="checkall()"/>
全选
</button>
<input id="Button2" type="button" onclick="uncheckall()" />
反选
</button>
<input type="checkbox" value="" name="a" />
b
<input type="checkbox" value="" name="a"/>
i
<input type="checkbox" value="" name="a"/>
u
<input type="checkbox" value="" name="a"/>
u
<input type="checkbox" value="" name="a" />
u
<input type="checkbox" value="" name="b"/>
u </div>
</form>
</body>
</html>
http://www.poluoluo.com/jzxy/201110/145127.html
http://blog.youkuaiyun.com/guoyz_1/article/details/5954243