javascript - Typescript 类中的 jQuery 回调

标签 javascript jquery callback typescript this

遇到了 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/

相关文章:

javascript - 循环 URL 并使用数组加载取决于 ID

javascript - 如何获取json数组?

javascript - 如何根据 ID 定位表,以便遍历其 td-spans、更改 span 颜色以及将其值提供给控制台

java - java中的回调行为

javascript - 应用过滤器的 ng-repeat 中的重复

javascript - 当用户从下拉菜单中选择选项时如何从数据库中打印记录?动态程序

jquery - 似乎无法让 jquery resize 事件在 Modernizr 媒体查询功能上工作

macos - 如何阻止CFSocket发送回调?

javascript - 如何在回调中访问正确的“this”?

javascript - JSON 和 Python Django - 无法解决同源问题 - 未调用回调函数