【发布时间】: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