在Typescript类中的jQuery回调

xDr*_*ing 2 javascript jquery callback this typescript

使用Typescript和jQuery时出现问题.元素会附加到正文并显示但单击按钮时没有任何反应.

我想它的this.fooClick()传递给按钮,但没有被调用或错误的jquery元素被保存到类变量.

有人帮吗?

test.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();
})
Run Code Online (Sandbox Code Playgroud)

test.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();
});
Run Code Online (Sandbox Code Playgroud)

Dav*_*ret 5

当你打电话时,.click()你想传递一个可以在单击按钮时执行的功能.现在你正在立即执行你的功能:

this.button = $('<button>').html("click").click(this.fooClick());
Run Code Online (Sandbox Code Playgroud)

...这将传中,结果this.fooClick()undefined.

您可以通过传入稍后将执行的函数来解决此问题:

this.button = $('<button>').html("click").click(() => this.fooClick());
Run Code Online (Sandbox Code Playgroud)

注意:如图所示,请确保使用箭头功能来保留上下文this.