【问题标题】:Pass separate scope in each new Instance created in ES6在 ES6 中创建的每个新实例中传递单独的范围
【发布时间】:2016-07-13 10:26:19
【问题描述】:

我写了一些代码如下。在这里,我正在为该类创建新实例 todos 并每次将单独的文本传递给构造函数。

setText 内部,我将一个点击方法绑定到元素test,以便在点击它时返回与其关联的文本。

这里的问题是,此方法创建的三个组件显示了单独的文本,但在单击任何元素时,它会将文本显示为'this is a todo component3',这是我传递给构造函数的最后一个文本。我希望它对每个组件都是分开的。请帮忙。

class todos{
  constructor(text){
    this.istodo = false;
    this.text = text;
  }
  _changestatus(){
    this.istodo = !this.istodo;
  }
  setText(){
    this.getDiv  = document.getElementById('test');
    this.getDiv.innerHTML = this.getDiv.innerHTML+'\n'+this.text;
    this.getDiv.onclick = (event)=> {alert(this.text)}; //this is always coming as "this is a todo component3"
  }
}


let todo = new todos('this is a todo component');
todo.setText();
let todo1 = new todos('this is a todo component1');
todo1.setText();
let todo2 = new todos('this is a todo component2');
todo2.setText();
let todo3 = new todos('this is a todo component3');
todo3.setText();

【问题讨论】:

  • 你一直在使用document.getElementById('test')
  • 是的,谢谢,我没有注意到那部分。

标签: javascript function scope ecmascript-6


【解决方案1】:

问题是您的所有文本只有一个容器,并且您添加的每个下一个待办事项都会覆盖由前一个创建的 onclick 处理程序。所以这就是问题所在。

要解决这个问题,您需要确保每个待办事项都为文本创建自己的容器。以下是一种可能的方法。请注意,我从 todos 类中删除了 document.getElementById('test')

    class todos {
      constructor(text) {
        this.istodo = false;
        this.text = text;
      }
      _changestatus() {
        this.istodo = !this.istodo;
      }
      setText() {
        this._node = document.createElement('div');
        this._node.appendChild(new Text(this.text));
        this._node.onclick = (event) => {
          alert(this.text)
        };
      }
      getNode() {
        return this._node;
      }
    }

    let container = document.getElementById('test');

    ['this is a todo component', 'this is a todo component #2', 'this is a todo component #3'].forEach(text => {
      let todo = new todos(text);
      todo.setText();
      container.appendChild(todo.getNode());
    });
<div id="test"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2014-05-20
    相关资源
    最近更新 更多