Jquery在初始页面加载时选中复选框时显示链接的代码

Jquery Code to show link while checkbox is checked on initial page load

本文关键字:复选框 显示 链接 代码 Jquery 加载      更新时间:2023-09-26

我有一段代码,当我选中或取消选中复选框时,它工作得很好,但当我最初加载页面时,我的一些复选框已经被选中,我想显示div框可见,但代码没有这样做,我遗漏了什么吗

请引导通过以下代码

感谢

$(document).ready(function() {
    //check the state of the checkox
    $(".showinvoice").is(':checked') {
        var stats = $(this).attr('data-id');
        $("#"+stats).css('display','block');
    }
    //check the code only when the click button is triggered    
    $(".showinvoice").click(function(e) {
        var getStudent = $(this).attr('data-id');
        if ($(this).is(':checked')) {
            $("#"+getStudent).css('display','block');
        } else {
            $("#"+getStudent).css('display','none');
        }
    });
});

首先,您缺少.showinvoice状态条件周围的if语句。

其次,您应该使用data()方法来访问data-*属性。在处理单选和复选框输入时,还应该使用change方法,以便使用键盘导航的用户仍然引发事件。最后,您可以删除if语句,而只使用toggle()

为了实现您所需要的,您所需要做的就是在页面加载时在复选框上引发一个change事件。试试这个;

// check the state of the checkox
if ($(".showinvoice").is(':checked')) {
    var stats = $(this).data('id');
    $("#" + stats).show();
}
// check the code only when the click button is triggered    
$(".showinvoice").change(function(e) {
    var getStudent = $(this).data('id');
    $("#" + getStudent).toggle(this.checked);
}).change(); // < to run this code when the page loads

尝试将第一部分更改为…

//check the state of the checkox
$(".showinvoice:checked").each(function() {
    var stats = $(this).data('id');
    $("#"+stats).css('display','block');
});