如何将 class 从 child 切换到 html 中的另一个

How to toggle class from a child to another in html

<html>
<head><title>Don't Know</title>
</head>
<body>
<div class="parent">
  <p class="child random">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
</div>
</body>
</html>

我想将 class“随机”从一个 child(p 标签)切换到另一个 child(p 标签)。我应该如何使用更少的 Javascript/Jquery 代码来做到这一点?

这样试试:

.random {
 color: red;
}
<html>
<head><title>Don't Know</title>
</head>
<body>
<div class="parent">
  <p class="child random">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
</div>
<script>
document.querySelectorAll(".child").forEach((child) => {
  child.onclick = () => {
     document.querySelector(".random").classList.remove("random");
     child.classList.add("random");
  };
});
</script>
</body>
</html>

单击 p 元素以从之前的位置删除 random class 并将其添加到新元素。

这个决定是我做的。

$('.child').on('click', function() {
  $('.child').removeClass('style_for_p');
  $(this).addClass('style_for_p');
});
.child {
  cursor: pointer;
}

.style_for_p {
  color: green;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent">
  <p class="child random">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
  <p class="child">Lorem Ipsum<p>
</div>

只需添加:

 const childEl = document.querySelectorAll(".child");
 childEl.forEach((child) => {
    child.addEventListener("click", () => {
        document.querySelector(".random").classList.remove("random");
        child.classList.add("random");
     });
 });