2016-11-11 61 views
0

我想有四個按鈕(在航空維修Builder調用導語),當我點擊任何一個,它會顯示一個特定的部分(格)和隱藏其它三個部分, ,所以一次只能顯示一個。優化顯示/隱藏多個div從不同的來源

這是我目前有:

<!--Photographer script--> 
<script> 
jQuery(document).ready(function(){ 
    jQuery("#bphotographer").click(function(){ 
     jQuery("#sclient").hide(); 
     jQuery("#sshoot").hide(); 
     jQuery("#sproduct").hide();   
    }); 
    jQuery("#bphotographer").click(function(){ 
     jQuery("#sphotographer").show(); 
    }); 
}); 
</script> 

<!--Client script--> 
<script> 
jQuery(document).ready(function(){ 
    jQuery("#bclient").click(function(){ 
     jQuery("#sphotographer").hide(); 
     jQuery("#sshoot").hide(); 
     jQuery("#sproduct").hide();   
    }); 
    jQuery("#bclient").click(function(){ 
     jQuery("#sclient").show(); 
    }); 
}); 
</script> 

<!--Shoot script--> 
<script> 
jQuery(document).ready(function(){ 
    jQuery("#bshoot").click(function(){ 
     jQuery("#sphotographer").hide(); 
     jQuery("#sclient").hide(); 
     jQuery("#sproduct").hide();   
    }); 
    jQuery("#bshoot").click(function(){ 
     jQuery("#sshoot").show(); 
    }); 
}); 
</script> 

<!--Product script--> 
<script> 
jQuery(document).ready(function(){ 
    jQuery("#bproduct").click(function(){ 
     jQuery("#sphotographer").hide(); 
     jQuery("#sclient").hide(); 
     jQuery("#sshoot").hide();   
    }); 
    jQuery("#bproduct").click(function(){ 
     jQuery("#sproduct").show(); 
    }); 
}); 
</script> 

這不是很優化,但它的工作原理,並沒有出現任何錯誤在Chrome的檢查小組。

你們是否有關於如何優化它有什麼建議?

如果你想要做的顯示和隱藏只有一格,你可以在你的菜單中單擊事件與div的ID同名添加屬性,並添加一個相同的類謝謝你,

理查德

回答

2

所有div在同一時間隱藏。

請嘗試以下:

$(".menu").click(function(){ 
 
    $(".tab").hide(); 
 
    $("#"+ $(this).attr("data-div")).show(); 
 
});
.menu{ 
 
    cursor:pointer; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="bphotographer" class="menu" data-div="sphotographer">bphotographer</div> 
 
<div id="bshoot" class="menu" data-div="sshoot">bshoot</div> 
 
<div id="bclient" class="menu" data-div="sclient">bclient</div> 
 
<div id="bproduct" class="menu" data-div="sproduct">bproduct</div> 
 

 

 
<div id="sphotographer" class="tab" style="display:none;height:100px;height:100px;background:blue"></div> 
 
<div id="sshoot" class="tab" style="display:none;height:100px;height:100px;background:red"></div> 
 
<div id="sclient" class="tab" style="display:none;height:100px;height:100px;background:yellow"></div> 
 
<div id="sproduct" class="tab" style="display:none;height:100px;height:100px;background:green"></div>

+0

那麼它是我花了一段時間才能得到它的工作。我正在使用一個網頁生成器,這使得難以實現你的代碼(data-div部分),但我終於解決了它。你的代碼非常棒!非常感謝你,我已經學會了如何實現一個onclick功能:) –

+0

不客氣:-) –