简体   繁体   English

jQuery:在单击ajax时,完成或失败的对象是否被单击?

[英]jQuery: On click ajax, get the clicked object in done/fail?

Simple ajax query, but being triggered for every item of a class using the .click() event. 简单的ajax查询,但使用.click()事件为类的每个项目触发。 When it gets to the .done() I cannot figure out how to look up the element which was clicked so I can properly remove the m_action class. 当到达.done()我无法弄清楚如何查找被单击的元素,因此我可以正确删除m_action类。

Below is the code. 下面是代码。 I'm sure I'm missing something simple, but I've been searching with Chrome and Firefox web tools without luck, and can't find a duplicate question here on Stack. 我确定我缺少一些简单的东西,但是我一直在用Chrome和Firefox网络工具进行搜索,但是没有运气,并且在Stack上找不到重复的问题。

In short: using the code below, how do I properly remove the m_action class of the clicked element on a successful jQuery ajax return? 简而言之: 使用下面的代码,如何在成功的jQuery ajax返回上正确删除clicked元素的m_action类?

<script type="text/javascript">
    jQuery("div#normal .m_action").click(function() {
        jQuery.ajax({
            url: "./action.php",
            type: "POST",
            data: { action: this.id }
        }).done(function(result) {
            jQuery(this).removeClass("m_action");
            jQuery(this).html(result);
        }).fail(function(result) {
            alert("There was an error.")
        });
    })
</script>

You can just store a reference to it so that it is available anywhere in that scope: 您可以只存储对它的引用,以便该范围内的任何地方都可以使用它:

jQuery("div#normal .m_action").click(function() {

    var elem = this; // <-- right here

    jQuery.ajax({
        url: "./action.php",
        type: "POST",
        data: { action: this.id }
    }).done(function(result) {
        jQuery(elem).removeClass("m_action"); // <-- elem is still available
        jQuery(elem).html(result); // <--
    }).fail(function(result) {
        alert("There was an error.")
    });
});

Just a note for the future, your problem doesn't have to do with jQuery. 只是对未来的说明,您的问题与jQuery无关。 This is just a simple use of variables within a scope. 这只是范围内变量的简单使用。 The this pointer changes within the done function, so you just needed to cache the reference. this指针在done函数内更改,因此您只需要缓存引用。

This code should work: 此代码应工作:

$(document).ready(function()
{
    jQuery(".m_action").click(function() {
        var self = $(this);
        jQuery.ajax({
            url: "./action.php",
            type: "POST",
            data: { action: this.id }
        }).done(function(result) {
            self.removeClass("m_action");
            self.html(result);
        }).fail(function(result) {
            alert("There was an error.")
        });
    })

});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM