我写了一些代码,如下所示。在这里我正在为该类创建新实例
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/