首页 > 解决方案 > 单击同一 div 中的另一个元素后如何选择特定元素

问题描述

我有一个 h3 元素和 ap 元素,它们位于 div 元素内,如下所示:

<div class="question">
    <h3> <a href="#"> *a question* <img class="arrow" src="" alt="an-arrow-img"> </img> </a> </h3>
    <p> *an answer* </p>
</div>

我的 css 文件中有一个名为“show”的类,如下所示:

//shows the answer when I click the h3 element
.show{
   display: block;
}

在网站上,我试图让问题答案看起来像这样:

显示隐藏 p 元素

在此处输入图像描述

当我单击问题(h3 元素)时,我使用 javascript 来切换“显示”类,但我将它们全部切换,无法弄清楚如何选择我点击的那个。到目前为止,我的 javascript 代码是这样的:

$("h3").on("click", function(){
   $("p").toggleClass("show");
});

是我的 HTML 结构错误,还是有办法组合 $(this) 选择器以仅显示我点击的问题的答案?

标签: javascripthtmljquerycss

解决方案


var question = document.getElementsByClassName("question");
var i;

for (i = 0; i < question.length; i++) {
  question[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var answer = this.nextElementSibling;
    if (answer.style.maxHeight) {
      answer.style.maxHeight = null;
    } else {
      answer.style.maxHeight = answer.scrollHeight + "px";
    } 
  });
}
.question {
  background-color: #2d6596;
  color: #f1f1f1;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: 1px solid white;
  text-align: left;
  outline: none;
  font-size: 15px;
  transition: 0.4s;
}

.active, .question:hover {
  background-color: #1a364f;
}

.question:after {
  content: '\002B';
  color: #f1f1f1;
  font-weight: bold;
  float: right;
  margin-left: 5px;
}

.active:after {
  content: "\2212";
}

.answer {
  padding: 0 18px;
  background-color: #f2f2f2;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
<button class="question">The question</button>
<div class="answer">
  <p>The answer</p>
</div>

<button class="question">The question</button>
<div class="answer">
  <p>The answer</p>
</div>

<button class="question">The question</button>
<div class="answer">
  <p>The answer</p>
</div>


推荐阅读