【发布时间】:2021-01-05 10:40:54
【问题描述】:
好的,到目前为止,我有这个页面,里面有几个按钮,当你点击按钮时它变成红色现在我想添加它,只要你点击它更多次,颜色就会改变。
例如:第一次按钮是绿色的,第一次点击它变成红色,第三次点击它变成粉红色等等。
我尝试使用我创建的 set_onclick 函数来执行此操作,然后使用多个此代码:
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
但我不让它工作
page();
function onbuttonclicked(a) {
document.getElementById("button" + a).classList.remove("button")
document.getElementById("button" + a).classList.add("clickedbutton")
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
function createButtons(amount){
for (var a = 1;a <(amount + 1); a++) {
var button = document.createElement("button");
button.classList.add("button")
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
set_onclick(amount);
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>buttons</title>
<link rel="stylesheet" type="text/css" href="buttons.css">
</head>
<body>
<div id="container"></div>
<script src="buttons.js"></script>
</body>
</html>
【问题讨论】:
标签: javascript button