javascript - 在 ES6 中创建的每个新实例中传递单独的作用域

标签 javascript function scope ecmascript-6

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

setText内部,我将一个click方法绑定(bind)到元素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();

最佳答案

问题是您只有一个容器来容纳所有文本,并且您添加的每一个下一个待办事项都会覆盖前一个待办事项创建的 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>

关于javascript - 在 ES6 中创建的每个新实例中传递单独的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38349034/

相关文章:

javascript - $watch 没有在函数之外更新数组?

c++ - 在 C++ 中将列表作为返回类型传递?

javascript - 为什么 javascript 会保留外部函数中发生的局部变量重新分配,而不必捕获返回值?

javascript - v-for 循环中的动态 V 模型名称 Vue 2

javascript - 将框架集与页面中的其他 HTML 元素一起使用

javascript - 网页无法从 Phonegap 中的远程服务器检索数据(但在 Chrome 中工作正常)

javascript - Javascript 中的 Math.Abs​​() - 数组意外

C语言 : Functions and "Format Type" Error

javascript - 如何在 Javascript 中创建 Scramble 函数

function - 如何为VLookup函数传入Range参数?