Friend
Friend

Reputation: 1346

jquery using $(this) not working

Hello people here is my code below..

$('.first').click(function(){

$('.second').each(function(){
console($(this));
});
});

i want to refer console($(this)); to $('.first') not the $('.second') .. i think we can do it through reference variable , but still not fixing :(

Upvotes: 0

Views: 4534

Answers (3)

Douglas
Douglas

Reputation: 37761

Since this depends on context, you could make this clearer by being explicit about what you expect this to be:

$('.first').click(function(){
  var first = this;
  $('.second').each(function(){
    console($(first));
  });
});

Upvotes: 0

friedi
friedi

Reputation: 4360

$('.first').click(function(){
  $('.second').each(function(){
    console($(this));
  }.bind(this));
});

Upvotes: 0

xdazz
xdazz

Reputation: 160833

$('.first').click(function(){
  var self = this;
  $('.second').each(function(){
    console($(self));
  });
});

or using jQuery.proxy() method:

$('.first').click(function(){
  $('.second').each($.proxy(function(){
    console($(this));
  }, this));
});

Upvotes: 2

Related Questions