简体   繁体   中英

How to use JQuery callback functions with Javascript objects

I have a Javascript object the following:

function extraFields(id) {
    this.numActiveFields = 0;

    ...

    this.addRow = function(quoteClass, rowClass) {
        var remButton = $("<span></span>")
        .addClass(rowClass)
        .addClass(quoteClass)
        .click(function() {
            //here I want to refer to the object's variable, but instead refer
            //to the JQuery object
            this.numActiveFields++;
        });
    }

    ...
}

I want to change the object's variable from inside the callback function. How would I do that? Should I change the way I declare the object?

When you are in the callback function "this" is the "remButton" you created. Just save "this" in a variable before the callback and then use that instead.

For a better explanation please look at the link that mplungjan suggested: Reference to an object from a callback function in jQuery

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