Problem with removing element
I don't know why this working:
$('.deleteQuestion').live('click', function(){
$.ajax({
type: 'GET',
url: '/delete_question/' + $(this).attr('name') + '/',
success: $('[wha开发者_如何转开发t="question"][name="' + $(this).attr('name') + '"]').remove()
});
});
but this not working:
$('.deleteQuestion').live('click', function(){
$.ajax({
type: 'GET',
url: '/delete_question/' + $(this).attr('name') + '/',
success: function(){$('[what="question"][name="' + $(this).attr('name') + '"]').remove();} }
});
});
Does someone know?
The success callback doesn't operate on the same this
that the click handler does. Save it in a variable:
$('.deleteQuestion').live('click', function(){
var element = $(this);
$.ajax({
type: 'GET',
url: '/delete_question/' + $(this).attr('name') + '/',
success: function(){ //this has to be a function, not a jQuery chain.
$('[what="question"][name="' + element.attr('name') + '"]').remove();}
}
});
});
In the first version $(this).attr('name')
is evaluated right away.
In the second version this
is not pointing to the current element since it only gets evaluated when the callback function executes, which is in a different context - so it won't work correctly.
I think in this instance neither are working as you intend.
In the first version, you have the following:
success: $('[what="question"][name="' + $(this).attr('name') + '"]').remove()
This is executed as soon as the line is reached and not on the success callback.
In the 2nd version, you lose the context of this in your callback:
success: function(){$('[what="question"][name="' + $(this).attr('name') + '"]').remove();}
Also, it looks like you have an additional end brace.
remove();} }
Try the following:
$('.deleteQuestion').live('click', function(){
var self = this;
$.ajax({
type: 'GET',
url: '/delete_question/' + $(this).attr('name') + '/',
success: function(){$('[what="question"][name="' + $(self).attr('name') + '"]').remove();}
});
});
this
is not pointing to what you what in the success function. Try this instead:
$('.deleteQuestion').live('click', function() {
var that = this;
$.ajax({
type: 'GET',
url: '/delete_question/' + $(this).attr('name') + '/',
success: function() {
$('[what="question"][name="' + $(that).attr('name') + '"]').remove();
}
});
});
精彩评论