【发布时间】:2021-08-17 23:59:13
【问题描述】:
希望你们都没事,在我下面的代码中: 用户每次点击元素 --> #crBtn,应该创建一个具有不同 id 的新按钮(但都具有相同的 className),例如,如果用户点击 #crBtn 三次,则意味着将出现 3 个按钮,现在,如果我点击这些按钮中的任何一个,我希望它改变它的背景颜色,同时我需要它的 id,我该如何在 js 中做到这一点?
var idNum = 0;
function crBtn()
{
idNum++;
var button = document.createElement("button");
button.innerHTML="HERE";
button.setAttribute("class","name");
button.setAttribute("id","na"+idNum);
document.body.appendChild(button);
}
.name
{
background-color: aquamarine;
border: none;
width:300px;
height: 50px;
cursor: pointer;
margin-right: 10px;
margin-bottom:10px;
}
#crBtn
{
width:500px ;
height:60px;
background-color: blue;
border: none;
margin:30px;
color:white;
font-size: 30px;
}
.name:hover
{
background-color: skyblue;
color:aliceblue;
}
<body>
<button id = "crBtn" onclick="crBtn()">CLICK TO CREATE BUTTONS</button><br>
</body>
【问题讨论】:
标签: javascript html css createelement