我现在用JavaScript制作了30个按钮,我希望所有按钮都像第一个按钮一样为绿色,每当您单击一个按钮时,它就会变成红色并保持红色。
由于某些原因,只有第一个按钮是绿色的,每当我单击它时,它都不会变成红色。我尝试button.style.backgroundColor = "red";
在函数中使用:单击时使按钮变为红色,但这不起作用
const color = ["green"];
page();
function onbuttonclicked() {
document.body.style.backgroundColor = color[nr - 1];
}
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function createButtons(amount) {
for (var a = 1; a < (amount + 1); a++) {
var button = document.createElement("button");
button.style.backgroundColor = color[a - 1];
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
set_onclick(amount);
}
<div id="container"></div>
编辑感谢所有的答案,是不可能只单击某些按钮时才更改某些按钮吗?因此,当我单击button1时,什么也没有发生,但是只要我单击按钮3,它就会变成红色
您需要nr
在onbuttonclicked
函数中作为参数传递
编辑:
OP评论:
好的,所以我需要添加一个参数。但我希望所有30个按钮均为绿色,因此当您打开页面时所有按钮均为绿色,这也与参数有关?
为此,在循环createButton中,将其更改color[a - 1]
为color[0]
const color = ["green"];
function onbuttonclicked(nr) {
document.body.style.backgroundColor = color[nr - 1];
}
function page() {
//style page
document.body.style.backgroundColor = "grey";
createButtons(30);
}
function set_onclick(amount, nr) {
for (let a = 1; a < (amount + 1); a++) {
document.getElementById(`button${a}`).setAttribute("onclick", `onbuttonclicked(${nr})`);
}
}
function createButtons(amount) {
for (let a = 1; a < (amount + 1); a++) {
const button = document.createElement("button");
button.style.backgroundColor = color[0];
button.id = `button${a}`;
button.innerHTML = `button ${a}`;
container.appendChild(button);
}
set_onclick(amount, 1);
}
page();
<div id="container"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句