首页 > 解决方案 > 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.

标签: javascripthtmlcss

解决方案


我想你想要这样的东西:

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

您再次在变量名中使用字符串模板,并期望它能够工作。

记得检查并理解你的控制台错误,当你做错语法时它们会告诉你。


推荐阅读