gpt4 book ai didi

javascript - 在 ES6 中创建的每个新实例中传递单独的范围

转载 作者:行者123 更新时间:2023-11-29 21:21:56 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com