猿问

单击同一 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 来切换类“show”,但我切换了所有这些问题,并且不知道如何选择我单击的那个。到目前为止,我的 JavaScript 代码是这样的:


$("h3").on("click", function(){

   $("p").toggleClass("show");

});

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


拉丁的传说
浏览 117回答 2
2回答

慕码人2483693

var question = document.getElementsByClassName("question");var i;for (i = 0; i < question.length; i++) {&nbsp; question[i].addEventListener("click", function() {&nbsp; &nbsp; this.classList.toggle("active");&nbsp; &nbsp; var answer = this.nextElementSibling;&nbsp; &nbsp; if (answer.style.maxHeight) {&nbsp; &nbsp; &nbsp; answer.style.maxHeight = null;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; answer.style.maxHeight = answer.scrollHeight + "px";&nbsp; &nbsp; }&nbsp;&nbsp; });}.question {&nbsp; background-color: #2d6596;&nbsp; color: #f1f1f1;&nbsp; cursor: pointer;&nbsp; padding: 18px;&nbsp; width: 100%;&nbsp; border: 1px solid white;&nbsp; text-align: left;&nbsp; outline: none;&nbsp; font-size: 15px;&nbsp; transition: 0.4s;}.active, .question:hover {&nbsp; background-color: #1a364f;}.question:after {&nbsp; content: '\002B';&nbsp; color: #f1f1f1;&nbsp; font-weight: bold;&nbsp; float: right;&nbsp; margin-left: 5px;}.active:after {&nbsp; content: "\2212";}.answer {&nbsp; padding: 0 18px;&nbsp; background-color: #f2f2f2;&nbsp; max-height: 0;&nbsp; overflow: hidden;&nbsp; transition: max-height 0.2s ease-out;}<button class="question">The question</button><div class="answer">&nbsp; <p>The answer</p></div><button class="question">The question</button><div class="answer">&nbsp; <p>The answer</p></div><button class="question">The question</button><div class="answer">&nbsp; <p>The answer</p></div>

小唯快跑啊

使用 JQuery.next() 选择 $this 的同级。$("h3").on("click", function(){&nbsp; &nbsp;$(this).next("p").toggleClass("show");});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答