实例说明扩展JQuery方式
如何擴(kuò)展Jquery?
1. 有兩種方式來(lái)擴(kuò)展JQuery,分別是:
$.extend(object): 為域名jQuery增加方法,為靜態(tài)方法,全局方法,任何人都可以調(diào)用,調(diào)用的時(shí)候,需要直接加上$或者jQuery前綴。
$.fn.extend(object): $.fn = $.prototype, 因此可以從這里看出,這張擴(kuò)展方式是在為每個(gè)jQuery對(duì)象增加方法,因?yàn)槊總€(gè)jQuery對(duì)象的實(shí)例,都可以獲得在這里擴(kuò)展的方案。調(diào)用的時(shí)候,不需要添加特殊的前綴,直接選取jQuery對(duì)象之后,就可以調(diào)用了。
2. jQuery是一個(gè)封裝的非常好的類,如果使用$(“#id”)可以生成一個(gè)jQuery對(duì)象,但是注意,jQuery對(duì)象并不是真正的HTML標(biāo)記所對(duì)應(yīng)的對(duì)象,而是包含一個(gè)標(biāo)記所對(duì)應(yīng)的數(shù)組,數(shù)組中的成員才是標(biāo)記所對(duì)應(yīng)的對(duì)象。
?
下面代碼可以演示這兩種方式:
<!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.")}});//以靜態(tài)方法的形式直接使用jquery本身的對(duì)象調(diào)用if ($.staticextend) {$.staticextend();} else {alert("There is not a function called staticextend in Jquery Object itself.");}//以靜態(tài)方法的形式直接調(diào)用jqueryextendif ($.jqueryextend) {$.jqueryextend();} else {alert("There is not a function called jqueryextend in Jquery Object itself. You must get wrong.");}//獲取一個(gè)jquery實(shí)例var jdiv = $(".idtest");//一個(gè)jquery實(shí)例本身包含了一個(gè)數(shù)組對(duì)象if (jdiv.length>1) {alert("we can see jdiv contains an array object!");}//如果jquery有多個(gè),需要這樣調(diào)用。jdiv.each(function() {alert("I am "+ $(this).attr("id")); //這里不能直接使用this,因?yàn)閠his是htmlelement,沒(méi)有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>如果擴(kuò)展jquery已經(jīng)存在的方法,比如拿jqgrid來(lái)說(shuō),如果你想修改某個(gè)方法,讓他在方法的執(zhí)行前后做些事情,這樣的話,我們可以這樣做:
var oldEditCell = $.fn.jqGrid.editCell; $.jgrid.extend({editCell: function (iRow,iCol, ed){var ret;// do someting beforeret = oldEditCell.call (this, iRow, iCol, ed);// do something afterreturn ret; // return original or modified results} });在這里,我們覆蓋了原始的editCell方法,你可以在這個(gè)方法的前后做些事情。
轉(zhuǎn)載于:https://www.cnblogs.com/kevinhigher/archive/2011/10/15/2213759.html
總結(jié)
以上是生活随笔為你收集整理的实例说明扩展JQuery方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 顺序表与链表的比较
- 下一篇: POJ2186——并查集+Tarjan算