tags:

views:

80

answers:

6

How to explain this statment

var a = $(this);

What will 'a' contain?

+3  A: 

As always, it depends.

According to the article, depending on where this line of code exists, this can be either a DOM object or a jQuery object.

Matthew Jones
A: 

a will reference a jQuery object of the object referenced by this. See the manual page about the jQuery object for further information.

Gumbo
A: 

It depends on the scope. $(this) gives you a jQueryified object that is based on whatever this is.

Andy Gaskell
A: 

That depends inside which function is that called, for example:

$("input#hello").click(function(){
    $(this).toggleClass("clicked");
});

In that case, $(this) will be the input selected by the locator outside of the function.

Santi
+1  A: 

Well, it depends on context it's being used in. In this instance:

$(function() {
    $('a').each(function() {
        var a = $(this);
    });
});

This bit of code loops through all the <a> tags on a page and on each loop, $(this) will be the current <a> tag. You can use all the jquery methods on that object. In this case a is just a link to $(this). So, instead of doing, for instance, $(this).hide() you can now do a.hide().

This is very basic jquery. You should find a nice beginners tutorial.

KyleFarris
+1  A: 

Here's an example:

$('#my_button').click(function() {
    $(this).hide();
});

In this code, $(this) will refer to the clicked button element. It's meaning depends on the current scope.

rogeriopvl