jQuery的阿贾克斯this.id不确定不确定、阿贾克斯、jQuery、id

由网友(温柔女杀手)分享简介:我有一个项目列表中删除我使用AJAX。I have a list of items I delete using AJAX.这名单是一个简单的列表,div的等时,该项目是由我还真数据库中删除每个div作为一个ID,然后将它删除就行了。This list is a simple list with divs and...

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

I have a list of items I delete using AJAX.

这名单是一个简单的列表,div的等时,该项目是由我还真数据库中删除每个div作为一个ID,然后将它删除就行了。

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.

下面我code:

HTML

<div id="row1">
<div>item1</div>
<div><a href="...">view</a></div>
<div><a id="1">delete</a></div>
</div>

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 是不确定的,为什么?我有 ID =1在我的A HREF。

For some reason the this.id does not work because this.id is undefined ... why? I have id="1" on my a href.

推荐答案

您正在使用的这指的是AJAX对象,因为那里是该函数中的一个新的范围。如果您要访问的变量outwide你的范围,你有AJAX调用之前申报。

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();
            }
        }
    });
});
阅读全文

相关推荐

最新文章