Reputation: 988
How do you create a jQuery plugin that is able to access other elements it's been applied to?
What is meant is, if a custom plugin is applied via $('selector').test(), test may add an event click to all elements matched by 'selector'.
Within this click event some action needs to be performed on all other elements matched by 'selector', what is the best way to go about doing this?
The following is a working example:
-
$.fn.test = function() {
var children = [];
return this.each(function(){
$(this).css('color','green').on('click',function() {
console.log(children);
});
children.push(this);
});
};
$('span').test()
Although this example works, is this best practice? The jQuery document on plugin development don't seem to cover this topic.
Any help would be appreciated, thanks.
Upvotes: 1
Views: 72
Reputation: 82297
It isn't bad practice per se, but it can be improved a little. Internally jQuery will iterate over a set, and the this
inside of the jQuery.fn
is the whole set of the selector response so you don't need to use each and then rewrap them individually
$.fn.test = function() {
var set = this;
return this.css('color','green').on('click',function() {
console.log(set.not(this));
});
};
$('span').test()
Upvotes: 1