如何在javascript中单击按钮更改类

发布于 2025-01-20 14:20:37 字数 842 浏览 1 评论 0原文

我有这个脚本,但是需要将课程更改为“ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_蜘蛛 2025-01-27 14:20:37

您将课程添加到单击按钮中,但切勿从另一个按钮中删除类。

var form = document.querySelector("form");
const goButton = document.querySelector("#go");
const stopButton = document.querySelector("#stop");

form.addEventListener("click", function(event) {
  event.preventDefault();
  if (event.target == goButton) {
    goButton.classList.add("go");
    stopButton.classList.remove("stop");
  } else if (event.target == stopButton) {
    stopButton.classList.add("stop");
    goButton.classList.remove("go");
  }
});
.go {
  background: green;
  color: white;
}

.stop {
  background: red;
  color: white;
}
<form action="">
  <button id="go">GO!</button>

  <button id="stop">STOP!</button>
</form>

You're adding the class to the clicked button, but never removing the class from the other button.

var form = document.querySelector("form");
const goButton = document.querySelector("#go");
const stopButton = document.querySelector("#stop");

form.addEventListener("click", function(event) {
  event.preventDefault();
  if (event.target == goButton) {
    goButton.classList.add("go");
    stopButton.classList.remove("stop");
  } else if (event.target == stopButton) {
    stopButton.classList.add("stop");
    goButton.classList.remove("go");
  }
});
.go {
  background: green;
  color: white;
}

.stop {
  background: red;
  color: white;
}
<form action="">
  <button id="go">GO!</button>

  <button id="stop">STOP!</button>
</form>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文