使用ajax的jquery选择器

时间:2013-11-27 21:02:41

标签: jquery ajax jquery-selectors

我有一个简单的.ajax函数,它在click事件中触发。该功能成功触发,我很难删除最近的<tr>标签以确认删除。

$('.delete_item').click(function () {
    if (confirm('Delete this location?')) {
        $.ajax({
            type: "POST",
            url: "/Admin/Location/Delete",
            data: "{id: '" + $(this).attr('id') + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "text",
            success: function (msg) {
                if (!msg) {
                    alert('There was an error deleting the location.');
                    return;
                }
                else {
                    $(this).closest('tr').css('background-color', '#df8f8f').delay(800).fadeOut('slow');
                }
            },
            error: function (msg) {
                alert('error in ajax call');
            },
        });
    }
    return false;
});

这是标记

<tr class="class">    
    <td style="width:300px;">Rosana Square</td>
    <td>24 Hours</td>
    <td style="width:300px;">8555 Monrovia</td>
    <td style="width:300px;">http://www.website.com</td>
    <td style="width:50px; text-align:center;"><a href="/Admin/Location/Edit/13"><span class="glyphicon glyphicon-edit"></span></a></td>
    <td style="width: 50px; text-align: center;"><a href="#_" id="13" class="delete_item"><span class="glyphicon glyphicon-trash"></span></a></td>
</tr>

这个ajax的内部this不再相关?我没有收到任何错误。有人可以识别我的错误吗?

2 个答案:

答案 0 :(得分:5)

ajax成功回调中的

this是你的问题,因为它没有引用元素,而是jqXhr对象。尝试在ajax设置或缓存上下文中设置上下文。

$('.delete_item').click(function () {
    if (confirm('Delete this location?')) {
        $.ajax({
            type: "POST",
            url: "/Admin/Location/Delete",
            data: "{id: '" + this.id + "' }",
            contentType: "application/json; charset=utf-8",
            context: this,      //<--- Set the context
            dataType: "text",
            success: function (msg) {
                if (!msg) {
                    alert('There was an error deleting the location.');
                    return;
                }
                else {
                    $(this).closest('tr').css('background-color', '#df8f8f').delay(800).fadeOut('slow');
                }
            },
            error: function (msg) {
                alert('error in ajax call');
            },
        });
    }
    return false;
});

或者

   $('.delete_item').click(function () {
       if (confirm('Delete this location?')) {
       var self = this; //Set it here
       ....
       ....

   success: function (msg) {
       if (!msg) {
          alert('There was an error deleting the location.');
           return;
       }
       else {
         $(self).closest('tr').css('background-color', '#df8f8f').delay(800).fadeOut('slow');
       }

另外在旁注中,您可以使用this.id代替$(this).attr('id')

答案 1 :(得分:1)

始终可以为this

设置上下文变量
var that = $(this);
$.ajax({
    ..
    ..
    success: function() {
        that.closest('tr').css(