jQuery ajax this.id undefined

我有一个使用AJAX删除的项目列表。

这个列表是一个简单的列表,其中包含div和每个div作为id,因此当从数据库中删除该项时,我返回true,然后删除该行。

这是我的代码:

HTML

item1

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(); } } }); }); 

由于某种原因, this.id不起作用,因为this.id未定义https://stackoverflow.com/questions/8186969/jquery-ajax-this-id-undefined/…为什么? 我的href上有id="1"

您正在使用的是指ajax对象,因为该函数中有一个新的作用域。 如果要在范围外访问变量,则必须在ajax调用之前声明它们。

 $('.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(); } } }); }); 

您的ID不应以数字开头。 以下是如何制定有效的ID: HTML中id属性的有效值是什么?

在您的成功回调函数中,这不会在您的单击处理函数中引用this 。 因此,您需要在单击处理程序中this进行引用,以便可以在回调函数中访问它:

 $('.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(); } } }); }); 
 $('.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(); } } }); }); 

尝试在$.ajax之前声明$this

喜欢:

var $ this = this;

并使用变量。

 $('.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(); } } }); }); 

我没有在你的html中看到任何带有’delete’类的元素。 假设它是删除链接,您需要使用$(this).attr('id')而不是this.id来获取id。