【问题标题】:Access property of an object from jquery function within the object (JavaScript/jQuery) [duplicate]从对象内的jquery函数访问对象的属性(JavaScript / jQuery)[重复]
【发布时间】:2022-01-16 10:45:51
【问题描述】:

我有以下课程:

class Traffic {
    constructor(name) {
        this.name = name;
    }
    setEventListeners() {
        $("#btn").on('click', function() {
            $(this).text(name);
        }
    }
}

点击<button id="btn"></button>时会抛出错误:name is undefined。这对我来说很有意义,因为我通常会使用 this.name 来访问对象的属性。不过因为我在jQuery里面,现在this指的是jQuery对象。

如何访问Traffic 对象的名称属性?

【问题讨论】:

    标签: javascript jquery class object


    【解决方案1】:

    您可以在函数外部声明一个新变量,其中this 仍然指向类实例。

    setEventListeners() {
        const name = this.name;
        $("#btn").on('click', function() {
            $(this).text(name);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 2013-07-17
      • 2019-02-04
      • 1970-01-01
      相关资源
      最近更新 更多