我被某件事困住了。我有一个表单,其中的字段仅在选中特定单选按钮时显示。当有人第一次使用以下代码填写表单时,这很容易。
HTML
<fieldset id="question">
<legend>This is my question</legend>
<label for="answerYes">Yes</label>
<input name="answer" id="answerYes" type="radio" value="1" />
<label for="answerNo">No</label>
<input name="answer" id="answerNo" type="radio" value="0" />
</fieldset>
jQuery
$("#subQuestion").hide();
$("#answerYes").click(function() {
$("#subQuestion").show();
});
$("#answerNo").click(function() {
$("#subQuestion").hide();
});
当有人返回表单进行编辑时,这种逻辑就会崩溃。在这种情况下,字段已预先填充,因此单击功能不存在。如果在页面加载时选中#answerYes,我如何使用 jQuery 显示#subQuestion。
最佳答案
尝试向您的页面添加 $(document).ready() 处理程序...
$(document).ready(function(){
// do your checks of the radio buttons here and show/hide what you want to
$("#subQuestion").hide();
if ($("#answerYes:checked").length > 0){ $("#subQuestion").show(); }
// add functionality for the onclicks here
$("#answerYes").click(function() {
$("#subQuestion").show();
});
$("#answerNo").click(function() {
$("#subQuestion").hide();
});
});
一旦页面完全加载(并动态预填充值),此处理程序就会触发
关于jquery - 如何使用jQuery根据单选按钮是否选中显示内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1947988/