遇到了 Typescript 和 jQuery 的问题。元素附加到正文并显示,但当我单击按钮时没有任何反应。
我想它与 this.fooClick() 有什么关系,它被传递给按钮但没有被调用,或者错误的 jquery 元素被保存到类变量中。
有人帮忙吗?
测试.ts
/// <reference path="jquery.d.ts" />
class foo {
private button;
private text;
constructor() {
this.button = $('<button>').html("click").click(this.fooClick());
this.text = $('<p>').html("foo");
$('body').append(this.button);
$('body').append(this.text);
}
public fooClick() {
$(this.text).html("bar");
}
}
$(function() {
var foobar = new foo();
})
测试.js
/// <reference path="jquery.d.ts" />
var foo = (function () {
function foo() {
this.button = $('<button>').html("click").click(this.fooClick());
this.text = $('<p>').html("foo");
$('body').append(this.button);
$('body').append(this.text);
}
foo.prototype.fooClick = function () {
$(this.text).html("bar");
};
return foo;
})();
$(function () {
var bar = new foo();
});
最佳答案
当您调用 .click()
时,您希望向其传递一个可以在单击按钮时执行的函数。现在你正在立即执行你的功能:
this.button = $('<button>').html("click").click(this.fooClick());
...这将传递 this.fooClick()
的结果,它是 undefined
。
你可以通过传入一个稍后将执行的函数来解决这个问题:
this.button = $('<button>').html("click").click(() => this.fooClick());
注意:如图所示,确保使用箭头函数来保留 this
的上下文。
关于javascript - Typescript 类中的 jQuery 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29659044/