HTTP
HTTP

Reputation: 1724

Jquery selector (this) not in function

I have a small code here that I cannot figure out if what is wrong, I think my code is okay but i suspect the this selector in jquery seems not in function after the .post request.

Here is my code:

$('.days').each(function() {
        day = jQuery.trim($(this).attr('id'));
        //this validates if there are events in this day
        $.post('includes/genAct.php', { thisDay: day, action: 'getMyEvent' }, function(data) {
            if(data != 0) {
                $(this).css('background', '#000').css('color', 'red');
            } 
        });
    });

If I make an alert of the returned data it seems gone working correctly. Is there any follow up ideas there. Thank you

Upvotes: 0

Views: 76

Answers (2)

Jude Duran
Jude Duran

Reputation: 2205

You can also use each function like this:

$('.days').each(function(i, val) {
 //the variable val returns the current element
});

You can use val instead of this.

i is the current index by the way.. :]

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

this is not a fixed variable, it changes depending on the context.

Inside the post success handler, it may not mean the same thing as outside it.

I would suggest caching the result:

var $this = $(this);

From that point on you can use $this to refer to the current element, no matter where you are within the each function.

Upvotes: 2

Related Questions