JQuery,如何在ajax调用后访问click对象?

时间:2011-09-20 21:15:35

标签: javascript jquery

这似乎应该是直截了当的,但我无法让它发挥作用。

我有一个.click绑定到某个类的许多按钮。单击该按钮时,它会将其id传递给$ .post调用以进行处理。

当$ .post调用成功返回时,我想删除该按钮并向容器添加消息,但我似乎甚至无法访问该按钮。

这是.click绑定:

$('.button').click(function() {
    $.post('process.php', {
        action: 'checkit'
    },
    function(result) {
        if (result == 'win') {
            // Access the button that was pressed with jQuery
        }
        else {
            alert("fail");
        }
    });
});

我已经尝试了,$(this),这个,并且在我输入初始点击功能时设置了一个像var trigger =这样的变量,但这些都没有起作用。我得到了未定义,或者指向实际的JQuery对象,而不是按钮。

有没有人能够深入了解我如何使用jQuery包装器访问当时点击的按钮,基本上类似$(触发按钮).html()以便我可以操纵正确的按钮?

感谢您的时间。

5 个答案:

答案 0 :(得分:4)

$('.button').click(function() {
    var clicked = $(this);
    ....

使用本地变量进行临时存储。

答案 1 :(得分:2)

试试这个

$('.button').click(function() {
    var $button = $(this);
    $.post('process.php', {
        action: 'checkit'
    },
    function(result) {
        if (result == 'win') {
            $button.doStuff();
        }
        else {
            alert("fail");
        }
    });
});

答案 2 :(得分:0)

这很容易做到:

$(this).foo('bar');

答案 3 :(得分:0)

$('.button').click(function() {
    $.post('process.php', {
        action: 'checkit'
    },
    function(result) {
        if (result == 'win') {
            $(this).html('something');
        }
        else {
            alert("fail");
        }
    }.bind(this));
});

工作?

答案 4 :(得分:0)

jsfiddle example你在尝试什么。单击文本。只需保留一个局部变量。