How do i refer to the $(this) element insidea $.post
I have this code
$.post("recommend.php",{"jid":jid,"vid":vid,"eid":eid},function(data){
if(data=="1")
{
$(this).text("Recommended");
}
else
{
$(thelink).text("Recommend");
}
});
the post is executed properly but the text on the link is NOT changing thou开发者_如何学Gogh data is equal to 1. Any help...
this
refers to the current context. In your AJAX callback it is different from the one of your calling function.
However, you can simply preserve it by using var $this = $(this);
and then use $this
inside the callback instead of $(this)
;
var $this = $(this);
$.post("recommend.php", {
"jid": jid,
"vid": vid,
"eid": eid
}, function (data) {
if (data == "1") {
$this.text("Recommended");
} else {
$(thelink).text("Recommend");
}
});
Of course another name would work, too. For example to preserve a plain this
lots of people use self
or that
.
Another solution would be using $.ajax({ context: this, ...... }));
to keep the same context inside the callback (if unspecified, this
points to the options object passed to $.ajax()
)
Set it to a variable before calling $.post
var that = $(this);
$.post(..., function() {
that.myFunction();
}
By default, this
inside an AJAX callback is the jqXHR
object for the request.
You should either cache the reference to the link (as you appear to have done with thelink
) or use the context
option to $.ajax
:
$.ajax({
url: "recommend.php",
type: 'POST',
data: {
"jid": jid,
"vid": vid,
"eid": eid
},
context: this,
success: function (data) {
if (data == "1") {
$(this).text("Recommended");
} else {
$(thelink).text("Recommend");
}
}
});
The context
option sets the context for the callback functions -- i.e. it defines this
within them. By setting it to the outer value of this
(the reference to the link), you can access the link with $(this)
within the callback.
精彩评论