如何向jQuery对象添加新方法? [英] How to add new methods to the jQuery object?

查看:110
本文介绍了如何向jQuery对象添加新方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为jQuery的对象添加方法?

Is there some way to add methods to jQuery's objects?

例如,我有jQuery对象

For example, I have jQuery object

a = $('div')

我是像那样被分配的每个对象都有特定的方法( doSomething())所以我可以像

I'd like that every object which was assigned like that, would have particular method (doSomething()) so I could invoke it like

a = $('.foo')
a.doSomething()

b = $('.bar')
b.doSomething()


推荐答案

你必须添加你的功能到 $。fn 命名空间。请注意,在函数内部,这个将引用jQuery对象,而不是DOM对象。

You have to add your function to the $.fn namespace. Please note that inside the function, this will refer to the jQuery object, not a DOM object.

$.fn.doSomething = function () {
    this.css('color', 'red');
};

$('#retk').doSomething();


jsFiddle演示

请阅读有关编写jQuery插件的信息

Please read about writing jQuery plugins for additional guidelines.

这篇关于如何向jQuery对象添加新方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆