I'm building an extended function to apply to any given element:
(function($){
$.fn.extend({
SomeFunction: function() {
var $this = $(this);
}
});
})(jQuery);
In a script tag, I would drop:
$(document).ready(function(){
$('.someclassname').SomeFunction();
});
This works fine, except that I want to be able to reference the scope of the function as the element and not as the function, as you can see in my one variable declaration. For some reason, it's not treating it like an element where I can apply things like:
$this.css('background','red');
In order for it to work, I have to change it to:
var $this = $('.someclassname');
How can I program the extended function so that $this refers to the element to which SomeFunction is being applied? I'd rather it not care what the class name is.
Thanks!
Within SomeFunction
, this
is not a DOM element, it's a jQuery instance. (Plugins are very different from event handlers.) That instance may have zero, one, or multiple matching DOM elements inside it.
So this.css("background", "red");
would work. E.g.:
(function($){
$.fn.extend({
SomeFunction: function() {
this.css("background", "red");
}
});
})(jQuery);
If your goal is to use the set from outside SomeFunction
(maybe SomeFunction
does filtering of some kind?), usually you'd do that by doing your filtering and returning the jQuery object with the (filtered) results. (If not filtering, the convention is to return this
[the full set].)
So for instance, suppose SomeFunction
is only supposed to return elements containing the text "kittens"
:
(function($){
$.fn.extend({
SomeFunction: function() {
return this.filter(function() {
return $(this).text().indexOf("kittens") !== -1;
});
}
});
})(jQuery);
Then:
$(document).ready(function(){
$('.someclassname').SomeFunction().css("background", "red");
});
would only affect elements with someclassname
that contained the text "kittens"
: Live Copy | Live Source