javascript - How to add a value of a variable to name of another one?
问题描述
I have the following JS code:
let itemsCount = 1;
addButton.onclick = () => {
itemsCount++;
let newElement + ${itemCount} = document.createElement("li");
newElement ${itemCount}.textContent = `thing_to_do ${itemCount}`;
parent.appendChild(newElement + ${itemsCount});
}
And have an 'onclick' event which increases the value of itemsCount
for 1 with each click and creates an li
element, and then appends to it the text, and I want each element to have its personal name which is: newElement
and then I want to add to this text a value of variable itemsCount
. But when I run the code, it gives me a syntax error and that is because of the ```${itemCount}.
Is there any way to add the itemCount
's value to the variable name, if it is possibe?
Will be thankful for any answer.
解决方案
我想你想要这样的东西:
let itemsCount = 0;
const addButton = document.getElementById("button");
addButton.onclick = () => {
itemsCount++;
let newElement = document.createElement("li");
newElement.textContent = `thing_to_do ${itemsCount}`;
document.getElementById("container").append(newElement)
}
<button type="button" id="button">add</button>
<ul id="container"></ul>
我更正了您的语法错误,并添加了一些 HTML 以供参考。
let newElement + ${itemCount}
您不能创建这样的变量,这只是不正确的语法。您正在使用没有反引号的字符串模板,并且在变量中,您不能这样做。
newElement ${itemCount}.textContent
您再次在变量名中使用字符串模板,并期望它能够工作。
记得检查并理解你的控制台错误,当你做错语法时它们会告诉你。
推荐阅读
- javascript - 如何使用来自另一个 file.js 的 div?[温泉]
- udp - ESP32 udp.write 发送数据包但增加数据包
- java - Android Spinner 不显示选定的文本
- html - 如何制作带有动画三行的下拉移动菜单?
- swift - 使用 id(Int32) 而不是 UUID SwiftUI 循环遍历核心数据
- java - 使用 iText 7 提取平面 PDF 表单的答案
- python - TypeError:泛型类型的参数必须是类型。有省略号
- excel - 将excel工作簿另存为pdf
- php - 如何在laravel中导入excel
- python - 将 wordcloud 颜色映射到情绪分析的值