我正在创建Q& A考试准备,有几个问题,每个问题后跟四个可能的答案,然后在答案下方有一个“答案”按钮,显示真实的答案。我把所有东西都搞定了,直到我意识到我有它,所以任何“答案”按钮都会切换所有内容DIV。如何使“答案”按钮仅切换打开之前的“内容”div?
请记住,我无法分配唯一ID,因为有数百个问题,我正在努力节省时间。
jQuery的:
$(function() {
$(".answer").click(function() {
$(".content").toggle("slow");
});
});
CSS:
div.content {
display: none;
width: 300px;
height: auto;
margin: 10px;
padding: 20px;
background: white;
border: 1px solid black;
cursor: pointer;
}
button.answer {
font-family: sans-serif;
font-weight: bold;
font-style: normal;
font-size: 0.92em;
line-height: 1.36em;
text-indent: 0em;
text-align: left;
color: #000000;
margin: 1em 0em 0em 2em;
}
HTML:
<div class="keep">
<p class="q"><samp class="q-no">1.</samp> Interpret the following directions:</p>
<p class="q-equation">i cap po qid × 10d</p>
<p class="an"><span class="choice">a.</span> Take one capsule by mouth four times a day for ten days.</p>
<p class="an"><span class="choice">b.</span> Take one capsule by mouth three times a day for ten days.</p>
<p class="an"><span class="choice">c.</span> Take one capsule by mouth twice a day for ten days.</p>
<p class="an"><span class="choice">d.</span> Take one capsule by mouth once a day for ten days.</p>
<div class="content">
<p class="anl"><b>a.</b> Take one capsule by mouth four times a day for ten days. Remember: <i>qd</i> is once a day, <i>bid</i> is twice a day, <i>tid</i> is three times a day and <i>qid</i> is four times a day.</p><a id="anchor-25-anchor"></a>
</div>
<button class="answer">Answer</button>
</div>
<div class="keep">
<p class="q"><samp class="q-no">2.</samp> Interpret the following directions:</p>
<p class="q-equation">ii tab po tid × 7d.</p>
<p class="an"><span class="choice">a.</span> Take two tablets by mouth four times a day for seven days.</p>
<p class="an"><span class="choice">b.</span> Take two tablets by mouth three times a day for seven days.</p>
<p class="an"><span class="choice">c.</span> Take two tablets by mouth twice a day for seven days.</p>
<p class="an"><span class="choice">d.</span> Take two tablets by mouth once a day for seven days.</p>
<div class="content">
<p class="anl" id="anchor-25-anchor"><b>b.</b> Take two tablets by mouth three times a day for seven days.</p><a id="anchor-26-anchor"></a>
</div>
<button class="answer">Answer</button>
</div>
答案 0 :(得分:5)
尝试使用.prev()
功能:
$(function() {
$(".answer").click(function() {
$(this).prev().toggle("slow");
});
});
如果.content
并非总是在.answer
之前,请改用.prev('.content')
。
答案 1 :(得分:0)
$(function() {
$(".answer").click(function() {
$(this).prev(".content").toggle("slow");
});
});
答案 2 :(得分:0)
您需要在点击处理程序中引用this
来标识点击的按钮,然后找到代表您要显示的内容的上一个兄弟:
$(".answer").click(
$(this).prev().toggle("slow");
);