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
精彩评论