可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a list of items I delete using AJAX.
This list is a simple list with divs and each div as an id so when the item is removed from the database I return true and then it removes the line.
Here my code:
HTML
JS
$('.delete').click(function () {
if (!confirm('Are you sure you want to delete?')) {
return false;
}
$.ajax({
type: "POST",
url: '/delete_record',
data: 'id=' + this.id,
cache: false,
success: function (result) {
if (result == 'good') {
$('#row' + this.id).remove();
}
}
});
});
For some reason the this.id does not work because this.id is undefined ... why? I have id="1" on my a href.
回答1:
The this you are using refers to the ajax object because there is a new scope within that function. If you want to access variables outwide your scope, you have to declare them before the ajax call.
$('.delete').click(function () {
if (!confirm('Are you sure you want to delete?')) {
return false;
}
var _this = this;
$.ajax({
type: "POST",
url: '/delete_record',
data: 'id=' + this.id,
cache: false,
success: function (result) {
if (result == 'good') {
$('#row' + _this.id).remove();
}
}
});
});
回答2:
Your ID should not start with a number. Here is how to formulate a valid id: What are valid values for the id attribute in HTML?
this within your success callback function does not refer to the this in your click handler function. So you need to make a reference to this in your click handler so it can be accessed in your callback function:
$('.delete').click(function () {
if (!confirm('Are you sure you want to delete?')) {
return false;
}
var that = this;
$.ajax({
type: "POST",
url: '/delete_record',
data: 'id=' + this.id,
cache: false,
success: function (result) {
if (result == 'good') {
$('#row' + that.id).remove();
}
}
});
});
回答3:
$('.delete').click(function () {
if (!confirm('Are you sure you want to delete?')) {
return false;
}
var id = this.id; // here is the magic
$.ajax({
type: "POST",
url: '/delete_record',
data: 'id=' + this.id,
cache: false,
success: function (result) {
if (result == 'good') {
$('#row' + id).remove();
}
}
});
});
回答4:
try to declare before the $.ajax the $this
like:
var $this = this;
and use the variable.
$('.delete').click(function () {
var $this = this;
if (!confirm('Are you sure you want to delete?')) {
return false;
}
$.ajax({
type: "POST",
url: '/delete_record',
data: 'id=' + $this.id,
cache: false,
success: function (result) {
if (result == 'good') {
$('#row' + $yourid).remove();
}
}
});
});
回答5:
I don't see any element with a class of 'delete' in your html. Assuming it's the delete link, you need to get the id with $(this).attr('id') instead of this.id.