javascript - 使用 jQuery 隐藏基于复选框的 div

标签 javascript jquery html

我有以下 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/

相关文章:

javascript - 无法让我的方法连接 2 个值

javascript - TypeError : elem. 自动完成不是一个函数

javascript - 从多个动态创建的 HTML 文本区域元素发布

javascript - 从 JSON API 响应获取属性的唯一值计数

javascript - 使用 `Observable` 代替 `$q.all`

html - 下拉表单,单击元素时,无需点击提交按钮即可转到链接

javascript - Skel js 折叠导航不工作 iOS

c# - HTML 代码到 C# StringBuilder 工具?

javascript - 如何通过组合在 React 组件之间共享 hooks

php - 在产品预览 slider 上显示图像