javascript - 如何在 javascript 中使用 for() 创建按钮的网格容器?
问题描述
我对 HTML 和 javascript 非常陌生,但我需要创建一个按钮网格容器,其中按钮上显示的文本是列表中的一个元素。换句话说,我需要每个按钮的文本彼此不同。我正在考虑使用 for 循环,但我不确定这是要走的路。我开始使所有按钮的文本相似,但它仍然无法正常工作。在这一点上的任何帮助或建议将不胜感激!!
.categories-buttons {
display: grid;
grid-template-columns: 80px 80px 80px 80px 80px;
}
.item {
padding: 10px;
}
<div class="categories-buttons">
<button id="demo" class="item"></button>
<script>
for (var i = 0; i < 20; i++) {
document.getElementById("demo")(7);
}
</script>
</div>
解决方案
假设您的列表是一个元素数组:
// This is javascript array of objects, each object has 1 property - buttonText.
// You can add more properties.
const elements = [
{ buttonText: 'Button 1' },
{ buttonText: 'Button 2' },
{ buttonText: 'Button 3' }
];
// Get parent div in which you want to add buttons
const parent = document.getElementById('buttons-container');
// In for loop, set "i" to be lower than number length of array.
for(let i = 0; i < elements.length; i++) {
// Create button node and add innerHTML (innerHTML is stuff that goes between <></> tags).
// Since "elements" is an array, you select current iteration of it with [i]
let button = document.createElement('button');
button.innerHTML = elements[i].buttonText;
parent.appendChild(button);
}
<div id="buttons-container"></div>
推荐阅读
- azure - 如何在逻辑应用中运行内联代码?
- openid - 诺克斯 OpenID 登录无限循环
- java - 如何将对象 ArrayList 中的 setText 设置为 TextView?
- javascript - 如何在 React 中加载 MathJax?
- python - 使用 categorical_crossentropy 预测的异常结果
- c# - 如何在 C# 中通过引用传递
- html - 我的照片库中有一个空白栏
- bash - 如何使用 Bash 脚本设置 curl 以下载文件
- mysql - 获取多列的计数并更新计数
- c# - 通过c#执行powershell脚本会抛出“
不被识别为 cmdlet 的名称”异常