.show
和 .hide
jQuery 代码适用于每个 <span>
同类.q_open
和 q_close
.我很清楚我的所有 <div>
标签的类别为 .answer
所以当我点击任何 <span>
时,它们会显示和隐藏这两个答案.有没有办法只引用一个 <div class=".answer">
当点击那个 <span>
标记而不是给每个 <div>
一个不同的class
?谢谢!
JavaScript 代码:
<script type="text/javascript">
$(function() {
$(".q_open").each(function() {
$(this).click(function() {
$(".answer").show();
});
})
$(".q_close").each(function() {
$(this).click(function() {
$(".answer").hide();
});
});
});
</script>
HTML代码:
<h2 class="question">
Q1: (the first question)
<span class="q_open"></span>
<span class="q_close"></span>
</h2>
<div class="answer" style="display: none;">
This should only open when clicked by the <span class="q_open"> for Q1.
</div>
<h2 class="question">
Q2: (the second question)
<span class="q_open"></span>
<span class="q_close"></span>
</h2>
<div class="answer" style="display: none;">
<p>
This should only open when clicked by the <span class="q_open"> for Q2.
</p>
</div>
最佳答案
我认为您正在寻找某种 Accordion 。为此,您需要定位要打开或关闭的确切 HTML 元素。
试试这个:
$(function() {
$(".q_open").click(function() {
// Select the related target to open
$(this).closest("h2").next(".answer").slideDown();
});
$(".q_close").click(function() {
// Select the related target to close
$(this).closest("h2").next(".answer").slideUp();
});
});
关于javascript - 使用 jQuery .hide/.show 仅显示和隐藏一个 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37536587/