[英]write a jquery function which accepts params and object
This should be an easy one. 这应该很容易。
How to write a jquery function that gets the 'calling' object and some params. 如何编写一个获取“调用”对象和一些参数的jQuery函数。
My function code: 我的功能代码:
new function($) {
$.fn.addcolor = function(param1, param2, param3, param4) {
// here i would like to retrieve the 'caller' object (div.foo in this case)
}
} (jQuery);
My code that 'calls' the function: 我的代码“调用”该函数:
$('div.foo').click(function() {
$(this).addcolor(1, 2, 3, 4);
});
I can get the params no problemo, but I want to get the content of the div.foo in the function and add some content it. 我可以毫无问题地获取参数,但是我想在函数中获取div.foo的内容并添加一些内容。
You're looking for this
. 您正在寻找
this
。
jQuery plugins in $.fn
are normal methods on the $
prototype. $.fn
中的jQuery插件是$
原型上的常规方法。 (jQuery assigns $.fn
to $.prototype
) (jQuery将
$.fn
分配给$.prototype
)
Like any other method, you can get the context in which it was invoked using this
. 与其他任何方法一样,您可以使用
this
获得在其中调用它的上下文。
In your addcolor
plugin, this
will represent the same jQuery object against which your plugin was called. 在您的
addcolor
插件中, this
将代表与您的插件相同的jQuery对象。
// v---jQuery object
$(this).addcolor(1, 2, 3, 4);
(function($) {
$.fn.addcolor = function(param1, param2, param3, param4) {
// here "this" is the same object
// this[ 0 ] to get the first DOM element
// this.each(function(... to iterate over the collection
}
})(jQuery);
In jQuery plugin functions that element is referenced by this. 在jQuery插件函数中,此元素引用此元素。
function($) {
$.fn.addcolor = function(param1, param2, param3, param4) {
// here i would like to retrieve the 'caller' object (div.foo in this case)
var divcontent = $(this).html();
}
} (jQuery);
this.whatever is one way... 这是一种方法...
There is also an arguments object that you can call. 您还可以调用一个arguments对象。 ie: arguments.length or arguments["parm"]
即:arguments.length或arguments [“ parm”]
To extend jQuery I used: 为了扩展jQuery,我使用了:
(function($) {
$.fn.extend({
addcolor: function(param1, param2, param3, param4) {
return this.empty().append(something);
}
});
})(jQuery);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.