Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何向jQuery对象添加新方法?_Javascript_Jquery Plugins_Methods_Jquery - Fatal编程技术网

Javascript 如何向jQuery对象添加新方法?

Javascript 如何向jQuery对象添加新方法?,javascript,jquery-plugins,methods,jquery,Javascript,Jquery Plugins,Methods,Jquery,有什么方法可以向jQuery的对象添加方法吗 例如,我有jQuery对象 a = $('div') 我希望这样分配的每个对象都有特定的方法(doSomething()),这样我就可以像这样调用它 a = $('.foo') a.doSomething() b = $('.bar') b.doSomething() 加起来像 $.fn.doSomething = function(data){ // data is the argument passed to doSomething

有什么方法可以向jQuery的对象添加方法吗

例如,我有jQuery对象

a = $('div')
我希望这样分配的每个对象都有特定的方法(
doSomething()
),这样我就可以像这样调用它

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

b = $('.bar')
b.doSomething()
加起来像

$.fn.doSomething = function(data){
    // data is the argument passed to doSomething
    return this.each(function(){
       var elem = $(this);
       //perform operation on elem
       // like to change background color use
       elem.css('background-color','red');

    });
}

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

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

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


请阅读更多指南。

我只想指出,这将影响创建的任何jQuery对象。@jAndy更新了答案,您现在可以检查并确认它是否正确。
.css()
方法在这里不是一个很好的示例,使用
.each()
毫无意义。