有沒有更好的方式來優化jQuery中的以下IF語句?更好的方法來優化IF語句
我不得不編輯下面的代碼幾次,這將是很好,如果我可以插在必要的值在一個不錯的陣列或東西...
$("#pmselect").change(function() {
if ($("#pmselect option:selected").attr("class") == "null") {
$('.avatar').hide();
$('.pmpass').hide();
$('.pmlogin').hide();
$('#nullavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "pm") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#pmavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "as") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#asavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "pn") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#pnavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "jm") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#jmavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "mh") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#mhavatar').show();
}
if ($("#pmselect option:selected").attr("id") == "rh") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#rhavatar').show();
}
if ($("#rmselect option:selected").attr("id") == "rm") {
$('.avatar').hide();
$('.pmpass').show();
$('.pmlogin').show();
$('#rmavatar').show();
}
});
switch/case語句? – ChuckE 2013-03-02 12:32:45
除了第一個「if」之外,您還根據元素的「id」進行選擇。爲此使用'switch'更清潔。 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/switch。還要考慮是否所有顯示/隱藏邏輯都可以移動到單獨的函數中,以便您可以將它與開關/ if語句分開 – thaJeztah 2013-03-02 12:34:26
改進已編寫和正在工作的代碼 - > http://meta.codereview.stackexchange.com/ – 2013-03-02 12:34:50