用js代码循环生成三个按钮,每个按钮用不同的颜色
时间: 2024-05-08 15:17:52 浏览: 21
以下是使用JavaScript循环生成三个颜色不同的按钮的代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Generate Buttons</title>
</head>
<body>
<!-- The div where the buttons will be generated -->
<div id="buttons-container"></div>
<script>
// The colors for the buttons
var colors = ["red", "green", "blue"];
// Get the buttons container
var buttonsContainer = document.getElementById("buttons-container");
// Loop through the colors and generate buttons
for (var i = 0; i < colors.length; i++) {
// Create a button element
var button = document.createElement("button");
// Set the button text
button.innerHTML = "Button " + (i+1);
// Set the button color
button.style.backgroundColor = colors[i];
// Add the button to the container
buttonsContainer.appendChild(button);
}
</script>
</body>
</html>
```
该代码将生成三个按钮,每个按钮的文本为“Button 1”,“Button 2”和“Button 3”,并分别使用红色,绿色和蓝色作为背景颜色。您可以修改“colors”数组中的颜色来使用不同的颜色。