如何扩展Jquery?
1. 有两种方式来扩展JQuery,分别是:
$.extend(object): 为域名jQuery增加方法,为静态方法,全局方法,任何人都可以调用,调用的时候,需要直接加上$或者jQuery前缀。
$.fn.extend(object): $.fn = $.prototype, 因此可以从这里看出,这张扩展方式是在为每个jQuery对象增加方法,因为每个jQuery对象的实例,都可以获得在这里扩展的方案。调用的时候,不需要添加特殊的前缀,直接选取jQuery对象之后,就可以调用了。
2. jQuery是一个封装的非常好的类,如果使用$(“#id”)可以生成一个jQuery对象,但是注意,jQuery对象并不是真正的HTML标记所对应的对象,而是包含一个标记所对应的数组,数组中的成员才是标记所对应的对象。
下面代码可以演示这两种方式:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<title></title>
<script type="text/javascript" src="../lib/jquery-1.6.3.js"></script>
<script type="text/javascript">
$(function() {
$.extend({
staticextend: function() {
alert("This is a static extend function, called staticextend.")
}
});
$.fn.extend({
jqueryextend: function() {
alert("all jquery object can call this function, and I am jqueryextend.")
}
});
//以静态方法的形式直接使用jquery本身的对象调用
if ($.staticextend) {
$.staticextend();
} else {
alert("There is not a function called staticextend in Jquery Object itself.");
}
//以静态方法的形式直接调用jqueryextend
if ($.jqueryextend) {
$.jqueryextend();
} else {
alert("There is not a function called jqueryextend in Jquery Object itself. You must get wrong.");
}
//获取一个jquery实例
var jdiv = $(".idtest");
//一个jquery实例本身包含了一个数组对象
if (jdiv.length>1) {
alert("we can see jdiv contains an array object!");
}
//如果jquery有多个,需要这样调用。
jdiv.each(function() {
alert("I am "+ $(this).attr("id")); //这里不能直接使用this,因为this是htmlelement,没有attr方法。
if (jdiv.staticextend) {
jdiv.staticextend();
} else {
alert("There is not a function called staticextend in jdiv ");
}
if (jdiv.jqueryextend) {
jdiv.jqueryextend();
} else {
alert("There is not a function called jqueryextend in jdiv. You must get wrong.");
}
});
});
</script>
</head>
<body>
<div id="one" class="idtest"></div>
<div id="two" class="idtest"></div>
</body>
</html>
如果扩展jquery已经存在的方法,比如拿jqgrid来说,如果你想修改某个方法,让他在方法的执行前后做些事情,这样的话,我们可以这样做:
var oldEditCell = $.fn.jqGrid.editCell;
$.jgrid.extend({
editCell: function (iRow,iCol, ed){
var ret;
// do someting before
ret = oldEditCell.call (this, iRow, iCol, ed);
// do something after
return ret; // return original or modified results
}
});
在这里,我们覆盖了原始的editCell方法,你可以在这个方法的前后做些事情。