jQuery的阿贾克斯this.id不确定 [英] jQuery ajax this.id undefined

查看:113
本文介绍了jQuery的阿贾克斯this.id不确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表中删除我使用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();
            }
        }
    });
});

这篇关于jQuery的阿贾克斯this.id不确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆