【问题标题】:Need help calling a method with a click event listener需要帮助调用带有单击事件侦听器的方法
【发布时间】:2019-02-09 05:47:36
【问题描述】:

非常想在我的类中调用 select 函数,得到错误告诉我 select in not defined。

我试过this.element,以及使用箭头函数来调用它。

class TabLink {
  constructor(element) {
    // Assign this.element to the passed in DOM element
    // this.element;
    this.element = element;
    // console.log(this.element);
    // Get the custom data attribute on the Link
    // this.data;
    this.data = this.element.dataset.tab
    // Using the custom data attribute get the associated Item element
    // this.itemElement;
    this.itemElement = document.querySelector(`.tabs-item[data-tab="${this.data}"]`);
    // Using the Item element, create a new instance of the TabItem class
    // this.tabItem;
    this.tabItem = new TabItem(this.itemElement);
    // Add a click event listener on this instance, calling the select method on click
    this.tabItem.addEventListener('click', select);
  };

  select() {
    // Get all of the elements with the tabs-link class
    const links = document.querySelectorAll('.tabs .tabs-links');

需要选择才能调用它。

【问题讨论】:

    标签: javascript class methods


    【解决方案1】:

    select是一个类方法,你需要把它作为一个对象属性来引用。

    this.tabItem.addEventListener('click', this.select.bind(this));
    

    如果方法中没有引用this,可以直接使用this.select而不是绑定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 2019-07-05
      • 2015-07-12
      • 2019-05-23
      相关资源
      最近更新 更多