javascript - 为动态创建的元素赋予不同的 ID
问题描述
所以,我有一个循环 10 次的函数,以创建 10 个元素。我想要完成的是:我想给那些div
Elements Different id
s,以便我可以在需要时单独访问它们。
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)
}
}
所以我想得到类似的东西,
- 第一个 div =
div id="sgId1"
- 第二格 =
div id="sgId2"
- 第三个 div =
div id="sgId3"
等。
注意:我只是从编码本身开始,目前进入 vanilla JS 的第 3 周。所以我不能使用任何库/框架
解决方案
使用循环中的 k 值来指定每个元素。
div.setAttribute("id","sgId"+k);
推荐阅读
- reactjs - 错误尝试导入错误:“NotificationsNoneIcon”未从“@material-ui/icons”导出
- google-bigquery - 如何在 BigQuery 中提取
- javascript - 光滑的滑块响应垂直:false 在 Chrome 中不起作用
- python - Python:如何根据条件重塑数据框?`
- sql - 如何使用查询验证数据库迁移?
- azure-devops - 我们如何通过 Azure DevOps REST API 创建 Azure 数据工厂管道?
- php - Apache Web 服务器上的 Azure DevOps 部署
- reactjs - KeyboardDatePicker:如何撤消最近日期的插入
- java - 我的项目点击导航抽屉不适用于片段。为什么?
- python - 为什么我的函数中的两个列表是相同的?