如何在javascript中单击按钮更改类
我有这个脚本,但是需要将课程更改为“ go”或“停止”。目前,我可以将两者都更改为课程,但应该更改为一个或另一个
代码
var form = document.querySelector("form");
form.addEventListener("click", function(event) {
event.preventDefault();
const classId = event.target.id;
if (classId == "go") {
event.target.className = "go";
} else if (classId == "stop") {
event.target.className = "stop";
}
});
.go {
background: green;
color: white;
}
.stop {
background: red;
color: white;
}
<form action="">
<button id="go">GO!</button>
<button id="stop">STOP!</button>
</form>
I have this script but need to have the class to be changed to "go" or "stop". currently I can turn both to change to the class but it should change to one or the other
Code
var form = document.querySelector("form");
form.addEventListener("click", function(event) {
event.preventDefault();
const classId = event.target.id;
if (classId == "go") {
event.target.className = "go";
} else if (classId == "stop") {
event.target.className = "stop";
}
});
.go {
background: green;
color: white;
}
.stop {
background: red;
color: white;
}
<form action="">
<button id="go">GO!</button>
<button id="stop">STOP!</button>
</form>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将课程添加到单击按钮中,但切勿从另一个按钮中删除类。
You're adding the class to the clicked button, but never removing the class from the other button.