简体   繁体   English

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

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

I have a following piece of code which works fine, when i check or uncheck the checkbox, but when i initially loads my page and some of my checkboxes are already checked, i want to show the div box to be visible but the code is not doing so, am i missing anything 我有以下一段代码可以正常工作,当我选中或取消选中复选框时,但是当我最初加载我的页面并且某些复选框已经被选中时,我想显示div框可见,但是代码不可见这样做,我有什么遗漏吗

please guide through the following code 请指导以下代码

Thanks 谢谢

$(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');
        }
    });
});

Firstly you're missing the if statement around the .showinvoice state condition. 首先,您缺少有关.showinvoice状态条件的if语句。

Secondly you should use the data() method to access data-* attributes. 其次,您应该使用data()方法访问data-*属性。 You should also use the change method when dealing with radio and checkbox inputs so that the events are still raised by users who navigate using the keyboard. 处理单选和复选框输入时,还应该使用change方法,以便使用键盘导航的用户仍会引发事件。 Lastly you can remove the if statement and just use toggle() instead. 最后,您可以删除if语句,而只需使用toggle()

To achieve what you require all you need to do is raise a change event on the checkboxes on load of the page. 要实现所需的全部功能,请在页面加载时在复选框上引发一个change事件。 Try this; 尝试这个;

// 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

Try changing your first part to... 尝试将您的第一部分更改为...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM