【问题标题】:Typescript / Jquery: accesing the class in a inner Jquery scopeTypescript / Jquery:在内部 Jquery 范围内访问类
【发布时间】:2017-10-05 00:26:57
【问题描述】:

我搜索了整个 stackoverflow,发现了很多帖子,所以我很确定它是重复的,但是我找不到任何对我来说很友好和清晰的帖子,可能是因为我对 typescript 很陌生。

我目前正在使用的是打字稿类,然后单击 Jquery。 通常 this 或 $(this) 用于获取 Jquery 项目,但在 TS 中,这通常是为类保留的:

当我使用 Jquery 时,this 会被 Jquery 对象替换。

所以我目前正在与:

HTML:

<a data-id="6" class="js-set-crime-option btn btn-primary">Kies</a>

TS:

class Dealers
{
    constructor() {
        $(".js-set-crime-option").click(this.set);
    }

    public set() {
        var a = $(this);
        alert(a.data("id"));

        debugger;
        // i want to call test here
    }

    public test(id: string) {
        alert("helooooooo" + id);
    }

}

如何在这个范围内调用测试?

编辑:我发现这不确定它是否是正确的解决方案

var me: Dealers;

class Dealers
{
    name:string = "friend";

    constructor() {
        $(".js-set-crime-option").click(this.set);
        me = this;
    }

    public set() {
        var a = $(this);
        me.test(a.data("id"));
    }

    public test(id: string) {
        alert("helooooooo" + id + this.name);
    }

}

【问题讨论】:

  • “通常 this 或 $(this) 用于获取 Jquery 项目,但在 TS 中,这通常是为类保留的”不是真的。此外,TypeScript 类是 JavaScript 类。

标签: javascript jquery typescript scope click


【解决方案1】:

您应该使用粗箭头符号来自动保留正确的“this”,但您的建议也应该有效,尽管在附加处理程序之前保存它更安全。

element.click( () => { this.test(id); } );

【讨论】:

    猜你喜欢
    • 2016-06-23
    • 2013-09-08
    • 1970-01-01
    • 2011-06-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 2013-05-07
    相关资源
    最近更新 更多