Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $(this) does not insert text into my element

I am currently adding flagging functionality to a project of mine, and I can't get jQuery's $(this) selector to work.

The goal of this is to change the text in the div from flag to flagged when the user clicks it, and the ajax query runs successfully. My HTML/PHP is:

<div class="flag" post_to_flag='".$post_to_flag."'>Flag</div>

And my javascript that deals with the div is:

$('.flag').live('click', function () {
    $.post('../php/core.inc.php', {
        action: 'flag',
        post_to_flag: $(this).attr('post_to_flag')
    }, function (flag_return) {
        if (flag_return == 'query_success') {
            $(this).text('flagged');
        } else {
            alert(flag_return);
        }
    });
});

I can't replace the text with flagged, but if I replace the this selector with the .flag selector, it will replace everything with the class of flag on the page.

I have checked, and the $(this) selector is getting the attribute of 'post_to_flag' just fine. Why is this happening, and how can I fix it?

like image 939
Andre Nagel Avatar asked Jan 27 '26 13:01

Andre Nagel


1 Answers

You should add a context variable:

$('.flag').live('click', function () {
    var $context = $(this);
    $.post('../php/core.inc.php', {
        action: 'flag',
        post_to_flag: $context.attr('post_to_flag')
    }, function (flag_return) {
        if (flag_return == 'query_success') {
            $context.text('flagged');
        } else {
            alert(flag_return);
        }
    });
});

You are calling multiple functions within your jQuery selection call. When you go into that $.post() function, your scope changes. this now refers to a different scope from when you were inside one().

@Moak's suggestion, if you set a variable to a jQuery object, it's probably best to denote the variable with a beginning $ just for potential clarity for future readers or yourself.

like image 155
SomeShinyObject Avatar answered Jan 29 '26 03:01

SomeShinyObject



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!