首页 > 解决方案 > 为动态创建的元素赋予不同的 ID

问题描述

所以,我有一个循环 10 次的函数,以创建 10 个元素。我想要完成的是:我想给那些divElements Different ids,以便我可以在需要时单独访问它们。

function addDay() {  
    for(k = 0; k < 10; k++){
        let div = document.createElement("div");
        div.style.background = "red"
        div.style.color = "white"
        div.style.width = "40px"
        div.style.height = "20px"
        div.style.margin = "0.5px"
        div.style.textAlign = "center"
        div.style.borderRadius = "6px"
        div.setAttribute("class", "studentGrades");
        div.setAttribute("id", "sgId")

        div.setAttribute("onclick", "averageFunc(this, Number(prompt('Please, enter number here')))");

        div.innerHTML = "0"

        document.querySelector("#container3").appendChild(div)
    }
}

所以我想得到类似的东西,

注意:我只是从编码本身开始,目前进入 vanilla JS 的第 3 周。所以我不能使用任何库/框架

标签: javascriptloopsdom

解决方案


使用循环中的 k 值来指定每个元素。

div.setAttribute("id","sgId"+k);

推荐阅读