jQuery ajax this.id undefined

Der*_*rek 12 ajax jquery

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

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

这是我的代码:

HTML

<div id="row1">
<div>item1</div>
<div><a href="...">view</a></div>
<div><a id="1">delete</a></div>
</div>
Run Code Online (Sandbox Code Playgroud)

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();
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

由于某种原因,这this.id是行不通的,因为this.id未定义......为什么?我有id="1"一个href.

Nie*_*els 14

您正在使用的是指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();
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)