单击时,我的 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
范围绑定(bind)到 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);
关于javascript - 从 Click 回调函数中访问 JQuery UI Widget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39053749/