Reputation: 72652
This should be an easy one.
How to write a jquery function that gets the 'calling' object and some params.
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.
Upvotes: 0
Views: 192
Reputation: 2713
To extend jQuery I used:
(function($) {
$.fn.extend({
addcolor: function(param1, param2, param3, param4) {
return this.empty().append(something);
}
});
})(jQuery);
Upvotes: 0
Reputation: 2738
this.whatever is one way...
There is also an arguments object that you can call. ie: arguments.length or arguments["parm"]
Upvotes: 1
Reputation: 44205
In jQuery plugin functions that element is referenced by this.
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);
Upvotes: 2
Reputation: 322452
In your addcolor
plugin, this
will represent the same jQuery object against which your plugin was called.
// 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);
Upvotes: 2
Reputation: 887275
You're looking for this
.
jQuery plugins in $.fn
are normal methods on the $
prototype. (jQuery assigns $.fn
to $.prototype
)
Like any other method, you can get the context in which it was invoked using this
.
Upvotes: 2