2014-03-27 172 views
2

我目前有这个代码&寻找展示的简单和更短的方式,隐藏&禁用我的元素更简单的方法...显示,隐藏和禁用元素

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

它正常工作,我“M只是寻找一个更简单的方法...如果你知道一个较短&更简单的方法,请分享...

+5

张贴在http://codereview.stackexchange.com/ –

+4

这个问题似乎是题外话因为它是关于代码优化 –

+0

好吧...没问题...谢谢你让我知道! – Norris

回答

2

使用muliple选择用逗号

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

而不是使用showhide用布尔检查您可以使用toggle的。

jQuery toggle可以用来对一个项目进行切换这样的可见性:$(".target").toggle();

+0

这也适用...非常感谢! – Norris

+0

但是'toggle'的一个问题是,它会切换'show \ hide' ...不检查它是否隐藏或不... – Norris

1

你可以用模块化的方法去。

将常用的东西写在函数中,并在需要时调用它们。

在维护代码时也是有帮助的。

这是您的简单求代码:

$("#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(); 
} 
+0

这也适用,我会尽量熟悉模块化方法..谢谢您! – Norris