---
title: "定义和扩展jquery 自定义函数"
author: "sntetwt"
date: "2011-09-11T10:20:55Z"
tags: []
categories: ["Web前端"]
slug: "jquery"
draft: false
lastmod: "2011-09-11T10:20:55Z"
id: 1170044
url: "https://sntetwt.iteye.com/blog/1170044"
---

**1、扩展jQuery自身之全局函数**

jQuery.logError={/\*log error\*/}

jQuery.logWarning ={/\*log warning \*/}

jQuery.logDebug ={/\*log debug \*/}

使用：jQuery.logError();

上面三个可以写成

jQuery.log= {

    Error:function(){/\*log error\*/},

    Warning: function(){/\*log warning \*/},

    Debug: function(){/\*log debug\*/}

}

使用：jQuery.log.Error();

jQuery.foobar={ /\*do foobar\*/}

使用：jQuery.foobar();

以上的方法等同于使用 jQuery. extend ()

jQuery. extend = {

    log: {    Error:function(){/\*log error\*/},

    Warning: function(){/\*log warning \*/},

    Debug: function(){/\*log debug\*/}

},

    foobar:function(){/\*do foobar\*/}

}

使用：

jQuery.log.Error();

jQuery.foobar();

**2、添加实例方法，扩展jQuery.fn**

jQuery.fn=jQuery.prototype

如：jQuery.fn.showMessage=function(){

alert(“message!!”)}

使用：$(“#div1”).showMessage();

l       this是对当前jQuery对象的引用

l       使用each迭代当前对象

l       插件方法必须返回一个jQuery对象