This is a simple question regarding $(this) and how it is defined and redefined in a chunk of code.
$('input').live('click', function() {
$(this).addClass('active');
if( question.find('.false').is(':visible') ){
question.find('.false').hide("blind",{},350);
}
})
$(this) is unambiguously the input on the second line. Now, when we start the if statement, I have a new point of interest: question.find('.false'). If $(this) does not change to the new definition, is there an easier way to refer to question.find('.false')?
A follow-up for clarity
If I want to refer to question.find('.false') a few times in a longer version of the loop above, what’s the best way to refer to it?
-
Define a new variable before the loop:
var qfalse = question.find('.false') if( qfalse...){...qfalse this, qfalse that... -
Something else?
thiswill keep it’s value until some new context redefinesthis(like in a.each()callback). It keeps it’s value everywhere in your function.You can do what you were trying to do a bit simpler. Rather than using the
iftest, just require the selector to be visible and only operate on the visible ones.In practice, you can call hide on all of them and the ones that are already hidden will be just ignored by the
.hide()method.If you want to use the same jQuery selector object in multiple places in your function and you can’t just chain multiple methods together, then you would just use a local variable to assign the selector to and then use that variable: