首页 > 解决方案 > 如何在 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>

标签: javascripthtmlcss

解决方案


假设您的列表是一个元素数组:

    // 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>


推荐阅读