javascript - jQuery $(this) does not insert text into my element -
i adding flagging functionality project of mine, , can't jquery's $(this)
selector work.
the goal of change text in div
flag
flagged
when user clicks it, , ajax query runs successfully. html/php is:
<div class="flag" post_to_flag='".$post_to_flag."'>flag</div>
and javascript deals 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 text flagged
, if replace this
selector .flag
selector, replace class of flag on page.
i have checked, , $(this)
selector getting attribute of 'post_to_flag' fine. why happening, , how can fix it?
you should add 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 calling multiple functions within jquery
selection call. when go $.post()
function, scope changes. this
refers different scope when inside one()
.
@moak's suggestion, if set variable jquery object, it's best denote variable beginning $
potential clarity future readers or yourself.
Comments
Post a Comment