使用jquery在ajax调用期间切换单击对象的类

时间:2013-11-20 15:38:26

标签: jquery ajax object click

当我使用jQuery进行Ajax查询时,我想在点击的对象上显示一个微调器。

这是我尝试过的:

$(document).ready( function() {
    $.ajaxSetup({
        cache:false,
        url:'./ajax.php',
        type:'POST',
        beforeSend:function(xhr){
            $(this).addClass('ui-ajax-loading')
        },
        complete:function(xhr){
            $(this).removeClass('ui-ajax-loading')
        }
    });
});

问题是$(this)没有引用被点击的对象。

有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

如果您想更改thisbeforeSend功能中complete的内容,可以设置AJAX请求的上下文选项。

示例:http://jsfiddle.net/LuP9C/1/

$.ajaxSetup({
    cache: false,
    url: '/echo/html/',
    type: 'POST',
    beforeSend: function (xhr) {
        $(this).addClass('ui-ajax-loading');
        $('p').text('Sending...');
    },
    complete: function (xhr) {
        $(this).removeClass('ui-ajax-loading');
        $('p').text('Complete!');
    }
});

$('button').on('click', function () {
    $.ajax({
        context: $(this),
        data: {
            html: 'Hello world!',
            delay: 1
        }
    });
});