我有以下 jQuery 代码:
<script> function hideMenteeQuestions() {
$("#menteeapp").hide();
$("textarea[name='short_term_goals']").rules("remove", "required");
$("textarea[name='long_term_goals']").rules("remove", "required");
}
function showMenteeQuestions() {
$("#menteeapp").show();
$("textarea[name='short_term_goals']").rules("add", {
required: true
});
$("textarea[name='long_term_goals']").rules("add", {
required: true
});
}
function hideMentorQuestions() {
$("#mentorapp").hide();
$("input[name='mentees']").rules("remove", "required");
}
function showMentorQuestions() {
$("#mentorapp").show();
$("input[name='mentees']").rules("add", {
required: true
});
}
</script>
<script>
$(document).ready(function(){
$("#mentee").change(function(){
if($(this).is(':checked')){
showMenteeQuestions();
}else{
hideMenteeQuestions();
}
});
$("#mentor").change(function(){
if($(this).is(':checked')){
showMentorQuestions();
}else{
hideMentorQuestions();
}
});
$('#mentee').change();
$('#mentor').change();
});
</script >
此外,这是我的复选框的 HTML:
<input type="checkbox" name="type[]" id="mentor" value="mentor"><span class="checkbox">Mentor</span>
<input type="checkbox" name="type[]" id="mentee" value="mentee"><span class="checkbox">Mentee</span>
它应该根据您选择的复选框隐藏某些 div。单击复选框时它会起作用。但是,我还想在页面加载时触发更改功能。出于某种原因,它只调用第一个更改函数,在本例中是针对 #mentee
的。如果我改变顺序,那么另一个就可以了。它永远不会进入第二个 change()
调用。
有什么想法吗?
最佳答案
您的描述表明您没有将 Javascript 正确包装到 document.ready()
函数中,即
$(document).ready(function() {
// your code here
});
我预计发生的情况是您的一个函数抛出异常,因为 DOM 尚未正确准备好。
即使您有有一个document.ready
处理程序,我认为关于异常的内容可能仍然是正确的——一些条件在两个函数中都失败了,但仅在第一次加载。
关于javascript - 使用 jQuery 隐藏基于复选框的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8593593/