简体   繁体   中英

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. 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.

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.

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?

<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. 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 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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