首页 > 解决方案 > 如何使用更改背景的 ForEach 按钮?

问题描述

我想用 JS 创建 4 个按钮,只使用 ForEach 更改容器的背景。我已经准备好使用 foreach 的 4 个按钮,但背景的颜色没有改变。有什么帮助吗?这是我的代码:

let color_ar = ["yellow", "green", "blue", "silver"];
let buttons_ar = ["btn btn-warning", "btn btn-success", "btn btn-primary", "btn btn-secondary"];
window.onload = function() {
    createBtn();
}

function createBtn() {
    buttons_ar.forEach(function(item, i) {
        document.querySelector("#id_container").innerHTML += `<button id="id_button" class="${item}">${color_ar[i]}</button>`
        document.querySelector("#id_button").addEventListener("click", function() {
            i = 0;
            document.querySelector("#id_container").style.background = color_ar[i++];
        });
    })
}

标签: javascript

解决方案


您正在使用id_button点击,它只适用于第一个项目,因为 ID 是唯一的。

这是一种做你想做的事的方法

const color_ar = ["yellow", "green", "blue", "silver"],
  buttons_ar = ["btn btn-warning", "btn btn-success", "btn btn-primary", "btn btn-secondary"];

function createBtn() {
  buttons_ar.forEach((item, i) => {
    document.querySelector("#id_container").innerHTML += `<button id="id_button" class="${item}">${color_ar[i]}</button>`
    document.querySelectorAll('.btn').forEach(el => el.addEventListener('click', e => e.currentTarget.parentElement.style.background = e.currentTarget.textContent))
  })
}

window.addEventListener('load', () => {
  createBtn();
})
<div id='id_container'></div>


推荐阅读