我正在进行一项基本调查,其中一个问题是是/否问题。如果用户选择否,我想在问题下方显示一个文本区域,供用户解释他/她不回答的原因。如果他们单击"is",文本框将保持隐藏状态(如果他们单击“否”并显示它,则文本框会隐藏)。
这是我的 HTML 片段(是的,我正在使用表格进行格式化:-)。在这种情况下,它节省了我的时间)。有 4 个是/否问题。这只是其中之一。它们之间唯一的区别是 id 名称(#explain1
、#explain2
、#explain3
、#explain4
)
<tr id="yesno1">
<!-- yes/no1 choices --> <!-- Yes(1) No(0) -->
<td class="center"><input name="yn1" value="1" id="yes1" type="radio"></td>
<td class="center"><input name="yn1" value="0" id="no1" type="radio"></td>
<!-- yes/no1 question -->
<td class="question">
Did you meet your goals during this program? (If no, explain.)
</td>
</tr>
<tr class="explain-box" id="explain1">
<td></td>
<td></td>
<td class="explain-text">
<textarea name="explain1" placeholder="Please explain..."></textarea>
</td>
</tr>
这是我的 jQuery。这适用于问题一:
$(function() {
$('.explain-box').hide();
$('#no1').click(function() {
$('#explain1').show();
});
$('#yes1').click(function() {
$('#explain1').hide();
});
});
我对 javascript 和 jquery 相当模糊,所以我的问题是如何在不输入每个是/否问题的每个 ID 的条件的情况下使 jquery 代码工作?我知道我可以以某种方式使用 this
,但我不知道该怎么做。有人可以提供在这种情况下使用的功能的想法吗?我是否应该硬着头皮输入每个问题条件,因为它只有 4 个问题?
最佳答案
尝试使用 starts with选择器:
$(function() {
$('.explain-box').hide();
$('[id^=no]').click(function() {
$(this).parents("tr").next(".explain-box").show();
});
$('[id^=yes]').click(function() {
$(this).parents("tr").next(".explain-box").hide();
});
});
关于javascript - jquery 函数根据选择的选项显示/隐藏文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15550689/