Reputation: 771
Im trying to figure this one out, but no joy yet. For reasons that I cant go into here, I need to use both "this" and another selector to bind a click event.. Example
$('mySelector').each(function(){
$(this, this.siblings('img')).bind('click', function(e){
e.preventDefault();
doStuffTo($(this));
});
});
But I cant figure out how to do it. Anyone have any idea how I would achieve it?
Upvotes: 1
Views: 263
Reputation: 31280
Instead, you could do this:
$('mySelector').each(function(){
$(this).siblings('img').andSelf()).bind('click', function(e){
e.preventDefault();
doStuffTo($(this));
});
});
Upvotes: 2
Reputation: 93674
Most of the jQuery methods (that don't return a value) are automatically applied to each element in the collection, so each()
is not necessary.
Combining siblings()
and andSelf()
, the code can be simplified to:
$('.mySelector').siblings('img').andSelf().click(function (e) {
e.preventDefault();
doStuffTo($(this));
});
Upvotes: 5
Reputation: 385144
It's not entirely clear what you're trying to do, but perhaps it's this:
var f = function(e){
e.preventDefault();
doStuffTo($(this));
};
$('mySelector').each(function() {
$(this).bind('click', f);
$(this).siblings('img').bind('click', f);
});
Upvotes: 1