欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

实例说明扩展JQuery方式

发布时间:2025/7/14 编程问答 30 豆豆
生活随笔 收集整理的这篇文章主要介绍了 实例说明扩展JQuery方式 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

如何扩展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.");}//以静态方法的形式直接调用jqueryextendif ($.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 beforeret = oldEditCell.call (this, iRow, iCol, ed);// do something afterreturn ret; // return original or modified results} });

在这里,我们覆盖了原始的editCell方法,你可以在这个方法的前后做些事情。


转载于:https://www.cnblogs.com/kevinhigher/archive/2011/10/15/2213759.html

总结

以上是生活随笔为你收集整理的实例说明扩展JQuery方式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。