stephen mc
stephen mc

Reputation: 771

Using "this" in a jquery multiple selector

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

Answers (3)

cdeszaq
cdeszaq

Reputation: 31280

Instead, you could do this:

$('mySelector').each(function(){
    $(this).siblings('img').andSelf()).bind('click', function(e){
        e.preventDefault();
        doStuffTo($(this));
    });
});

Upvotes: 2

David Tang
David Tang

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

Lightness Races in Orbit
Lightness Races in Orbit

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

Related Questions