javascript - 单击同一 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) 选择器以仅显示我点击的问题的答案?
解决方案
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>
推荐阅读
- javascript - 无法将视频从网页流式传输到 python 服务器起诉 python 服务器中的 flask-socketio 和 java 脚本中的 socetio
- c - 在管道中,我发送了一些东西,但收到了不同的东西
- sendgrid-api-v3 - SendGrid 抑制/反弹没有结果 []
- c# - 当我在 DataGridView 中单击搜索数据按钮时,它会在 DataGridView 中添加我想要搜索的内容
- mongodb - 找不到“mongodb-org-tools”的版本“100.2.1”
- azure - 未在 azure linux 应用服务上添加缓存控制标头
- amazon-web-services - 将图像从一个 S3 存储桶复制到 diff 帐户 s3 存储桶
- firebase - (颤振)多邻国定时器
- reactjs - 当他们都是反应组件时分配给孩子什么类型
- r - 带有 for 循环的 Ploty R add_trace 覆盖来自 get(Variable) 的跟踪