如何制作一个更改另一个元素的 class 的按钮?

how to make a button that changes the class of another element?

我需要一个按钮来改变不同元素的class,我试过这样:

<button id="class-button">class change</button>
<div id="title">this is the title</div>

<script>
    document.getElementById("class-button").addEventListener("click", () => {
    document.getElementById("title").event.target.classList.add("the-class")
    }
</script>

失败了。

没有 event 属性 个 HTMLElement

如果要向元素添加 class,去掉 event.target 并简单地执行以下操作:

.the-class{
  color:red;
}
<button id="class-button">class change</button>
<div id="title">this is the title</div>

<script>
  document.getElementById("class-button").addEventListener("click", () => {
    document.getElementById("title").classList.add("the-class");
  })
</script>

也许你可以将你的JS放在onclick参数中。

<input type="Button" value="Click Me" onclick="document.getElementById('YourId').classList.add('className');" />

所以我发现您的代码有两个问题:

  1. 您不需要 .event.target,因为您不是在寻找活动。这意味着您可以删除 .event.target.

  2. 此外,您还没有关闭事件侦听器,这意味着它缺少右括号(这会导致语法错误)。

解决方案是:

document.getElementById("class-button").addEventListener("click", () => {
  document.getElementById("title").classList.add("the-class");
});
body {
  font-family: sans-serif;
}
.the-class {
  color: blue;
}
<h1 id="title">Keep on coding!</h1>
<button id="class-button">Change To Blue</button>