[英]Access JQuery UI Widget from within Click callback function
单击时,我的JQuery-UI小部件应将div附加到自身。 但是我的按钮回调没有访问this.element
-它是未定义的,因为我认为this
是指按钮而不是我的小部件。 请查看下面的简单代码以获得更好的描述:
(function ($) {
$.widget( "my.myWidget", {
_create: function () {
this.element.click(this.addRow);
},
addRow: function(evt) {
// this.element is undefined?
console.log("Is this.element defined: " + this.element != undefined);
// cant append to this.element
$('<div></div>')
.appendTo(this.element);
}
});
})(jQuery);
如何在点击回调函数中访问小部件( this.element
)?
它不起作用的原因是因为this.element.click
侦听器回调是在不同范围内调用的。 因此, addRow
的作用域不是小部件。
解决此问题有两种方法。
方案1:通过存储this
变量中,这样你就可以从另一个范围内访问它。 例如:
(function ($) {
$.widget( "my.myWidget", {
_create: function () {
var self = this;
this.element.click(function() {
self.addRow();
});
},
addRow: function(evt) {
// this.element is undefined?
console.log("Is this.element defined: " + this.element != undefined);
// cant append to this.element
$('<div></div>')
.appendTo(this.element);
}
});
})(jQuery);
选项2:通过将this
范围绑定到this.addRow
函数对象:
(function ($) {
$.widget( "my.myWidget", {
_create: function () {
this.element.click(this.addRow.bind(this));
},
addRow: function(evt) {
// this.element is undefined?
console.log("Is this.element defined: " + this.element != undefined);
// cant append to this.element
$('<div></div>')
.appendTo(this.element);
}
});
})(jQuery);
您应该声明此对象的另一个对象以在回调中使用它:
var _this = this;
在窗口小部件类的第一行定义它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.