如何使用 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++];

        });

    })

}


一只萌萌小番薯
浏览 126回答 1
1回答

慕田峪7331174

您使用的id_button是点击,它仅适用于第一项,因为 ID 是唯一的。这是一种做你想做的事的方法const color_ar = ["yellow", "green", "blue", "silver"],&nbsp; buttons_ar = ["btn btn-warning", "btn btn-success", "btn btn-primary", "btn btn-secondary"];function createBtn() {&nbsp; buttons_ar.forEach((item, i) => {&nbsp; &nbsp; document.querySelector("#id_container").innerHTML += `<button id="id_button" class="${item}">${color_ar[i]}</button>`&nbsp; &nbsp; document.querySelectorAll('.btn').forEach(el => el.addEventListener('click', e => e.currentTarget.parentElement.style.background = e.currentTarget.textContent))&nbsp; })}window.addEventListener('load', () => {&nbsp; createBtn();})<div id='id_container'></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript