Question

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 :(

Was it helpful?

Solution

$('.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));
});

OTHER TIPS

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

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));
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top