如何将 JQuery 回调函数与 Javascript 对象一起使用
我有一个 Javascript 对象如下:
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在回调函数中时,“this”就是您创建的“remButton”。只需在回调之前将“this”保存在变量中,然后使用它即可。
要获得更好的解释,请查看 mplungjan 建议的链接:
从 jQuery 中的回调函数引用对象
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