更简单的显示、隐藏方式&禁用元素

Simpler way of showing, hiding & disabling elements

本文关键字:amp 元素 方式 显示 隐藏 更简单      更新时间:2023-09-26

我现在有这个代码&寻找一种更简单、更短的显示、隐藏&禁用我的元素。。。

$("#chReportData").click(function () {
    if ($(this)[0].checked) {
        $("#reportDataOptions").show();
    } else {
        $("#ReportDataStatusOptions").hide();
        $("#reportDataOptions").hide();
        $('#chkReportPermission').attr('checked', false);
        $('#chReportDataStatus').attr('checked', false);
        $('#chReportDataCummulative').attr('checked', false);
        $('.allowedUpload').attr('checked', false);
        $('.allowedDelete').attr('checked', false);
    }
});
$("#chReportDataStatus").click(function () {
    if ($(this)[0].checked) {
        $("#ReportDataStatusOptions").show();
    } else if ($('#chReportDataCummulative').is('checked')) {
        $("#ReportDataStatusOptions").hide();
        $('.allowedUpload').attr('checked', false);
        $('.allowedDelete').attr('checked', false);
    } else {
        $("#ReportDataStatusOptions").hide();
        $('.allowedUpload').attr('checked', false);
        $('.allowedDelete').attr('checked', false);
    }
});

它运行良好,我只是在寻找一种更简单的方法。。。如果你知道一个较短的&更简单的方式,请分享。。。

您可以使用toggle,而不是使用带有布尔值检查的showhide

jQuery切换可以用于切换项目的可见性,如下所示:$( ".target" ).toggle();

使用逗号分隔的多个选择器

 $("#ReportDataStatusOptions , #reportDataOptions").hide();
 $('#chkReportPermission , #chReportDataStatus , #chReportDataCummulative , .allowedUpload , .allowedDelete').attr('checked', false);

您可以采用模块化方法。

在函数中编写常见的东西,并在需要的地方调用它们。

它在维护代码的同时也很有帮助。

这是您的简化代码:

$("#chReportData").click(function () {
    if ($(this)[0].checked) {
        $("#reportDataOptions").show();
    } else {
        hide_ReportDataStatusOptions();
        $("#reportDataOptions").hide();
        uncheck_chReportRbtns();
        uncheckAllowedRbtns();
    }
});
$("#chReportDataStatus").click(function () {
    if ($(this)[0].checked) {
        $("#ReportDataStatusOptions").show();
    } else if ($('#chReportDataCummulative').is('checked')) {
        hide_ReportDataStatusOptions();
        uncheckAllowedRbtns();
    } else {
        hide_ReportDataStatusOptions();
        uncheckAllowedRbtns();
    }
});

以及相应的功能:

function uncheck_AllowedRbtns(){
    $('.allowedUpload, .allowedDelete').attr('checked', false);    
}
function uncheck_chReportRbtns(){
    var txt = ['Permission', 'DataStatus', 'DataCummulative'];
    for(var i=0; i<txt.length; i++){
        $('#chReport'+txt[i]).attr('checked', false);
    }
}
function hide_ReportDataStatusOptions(){
    $("#ReportDataStatusOptions").hide();
}