首页 > 解决方案 > 如何将“this”绑定到单击侦听器并使用事件 - es6

问题描述

我有一个多步表单,有 4 个框架集。当我按下“下一步”按钮时,每个人都必须进来(当然)

我的 ES6 模块化代码包含如下内容:

class FormController {
  // 1. describe and initiate object
  constructor() {
    this.nextBtn = $(".next");
    this.next_fs;
    .... 

    this.events();
  }

  // EVENTS LISTENER
  events(){
    this.nextBtn.on("click", this.nextClicked.bind(this));
    // other listeners
  }

  nextClicked() {
    this.next_fs = $(this)
      .parent()
      .next(); // this is the next fieldset
    // some actions...
  }
// rest of the code
}

我的问题如下:我需要在nextClicked函数内部绑定“this”才能使用所有变量和方法,如this.next_fs,this.saveData()等...

但是我还需要知道哪个按钮被点击了,我不知道因为this没有更多的“这个按钮”,我不能传递一个变量(我们称之为'e')来跟踪e.target。

我的代码有什么问题?我知道这是我没有看到的愚蠢的东西。

谢谢!

标签: javascriptecmascript-6event-listeneres6-class

解决方案


但是我还需要知道哪个按钮被点击了,我不知道因为“this”不再是“this button”,而且我不能传递一个变量(我们称之为'e')来跟踪e.target

浏览器的事件触发代码通过了它。你只需要阅读它。

nextClicked(e) {

推荐阅读