javascript - 如何使用更改背景的 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++];
});
})
}
解决方案
您正在使用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>
推荐阅读
- reactjs - 返回值形式如何使用钩子
- sql - LEFT JOIN 上的 SQLITE 列未填充
- c# - 丢弃 DoAwait() VS Task.Run(() => DoAwait()) 有什么区别
- python - 如何使用 requests 库发送和接收请求?
- c - GCC:如何从不同类型的匿名结构初始化变量
- udp - 如果没有连接,udp 如何接收消息?
- javascript - 如何连接到 json-rpc 的 SLOBS 管道?
- ruby-on-rails - 我需要做什么才能在 nginx 和 puma 上连接 ActionCable?
- javascript - Promise.all 是否并行运行承诺?
- python - 尝试为大型数据集(400 万行)优化 Python for 循环