Why is my jQuery having an error when I put this line in?
<script type="text/javascript">
$(function(){
$(".arrowbutton").click(function(){
id = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/upvote",
data:{'id':id},
beforeSend:function() {
},
success:function(html){
$(this).hide();
}
});
return false;
开发者_Python百科 });
});
</script>
When I remove $(this).hide();
it's fine. But, I want it to hide!!!
Because this
doesn't refer to you arrow button, but it refers to the AJAX Request object.
$(".arrowbutton").click(function(){
var that = this;
var id = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/upvote",
data:{'id':id},
beforeSend:function() {
},
success:function(html){
$(that).hide();
}
});
return false;
});
jQuery calls your success
function more or less like this:
handleSuccess: function( s, xhr, status, data ) {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( s.context, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
}
},
The first argument of the call method sets the this
keyword in the success function to s.context
Because $(this)
doesn't return what you think it does in the success callback. You could use a closure:
$(function(){
$('.arrowbutton').click(function(){
var button = $(this);
$.ajax({
type: 'POST',
url: '/upvote',
data: { id: this.rel },
beforeSend:function() {
},
success:function(html) {
button.hide();
}
});
return false;
});
});
$(this)
is referring to the Ajax request, not the surrounding button.
Try using a closure like so:
<script type="text/javascript">
$(function(){
$(".arrowbutton").click(function(){
var arrowbutton = $(this);
id = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/upvote",
data:{'id':id},
beforeSend:function() {
},
success:function(html){
arrowbutton.hide();
}
});
return false;
});
});
</script>
"this" does mean this in all situations, because you are inside a new function that is the new this.
Check this tutorial out to learn all the different ways you can deal with it:
- http://justin.harmonize.fm/index.php/2009/09/an-introduction-to-javascripts-this/
精彩评论