这就是我所拥有的:
(category=="Ljud & Bild")?byId("nav_sub_ljud_bild").style.display='block' : byId("nav_sub_ljud_bild").style.display='none';
(category=="Datorer")?byId("nav_sub_datorer").style.display='block' : byId("nav_sub_datorer").style.display='none';
(category=="Telefoner & Fax")?byId("nav_sub_telefoner").style.display='block' : byId("nav_sub_telefoner").style.display='none';
(category=="Överlåtelser")?byId("nav_sub_overlatelser").style.display='block' : byId("nav_sub_overlatelser").style.display='none';
(category=="Fastigheter & Lokaler")?byId("nav_sub_fastigheter").style.display='block' : byId("nav_sub_fastigheter").style.display='none';
(category=="Inventarier/Inredning")?byId("nav_sub_inventarier").style.display='block' : byId("nav_sub_inventarier").style.display='none';
(category=="Tjänster")?byId("nav_sub_tjanster").style.display='block' : byId("nav_sub_tjanster").style.display='none';
(category=="Resor & Biljetter")?byId("nav_sub_resor").style.display='block' : byId("nav_sub_resor").style.display='none';
(category=="Sport & Träning")?byId("nav_sub_sport").style.display='block' : byId("nav_sub_sport").style.display='none';
(category=="Böcker & Litteratur")?byId("nav_sub_litteratur").style.display='block' : byId("nav_sub_litteratur").style.display='none';
(category=="Djur")?byId("nav_sub_djur").style.display='block' : byId("nav_sub_djur").style.display='none';
(category=="Musik-Instrument")?byId("nav_sub_musik_instrument").style.display='block' : byId("nav_sub_musik_instrument").style.display='none';
(category=="Hobby & Samlarobjekt")?byId("nav_sub_samlarobjekt").style.display='block' : byId("nav_sub_samlarobjekt").style.display='none';
(category=="Smycken & Klockor")?byId("nav_sub_juveler").style.display='block' : byId("nav_sub_juveler").style.display='none';
(category=="Leksaker & Barn-artiklar")?byId("nav_sub_leksaker_barn").style.display='block' : byId("nav_sub_leksaker_barn").style.display='none';
(category=="Vuxen-plagg")?byId("nav_sub_vuxen_plagg").style.display='block' : byId("nav_sub_vuxen_plagg").style.display='none';
你会怎么写这个?上面这个看起来太“丑陋”了!
谢谢
最佳答案
我假设这是由 PHP 生成的 JavaScript。 为了保持可维护的 PHP 文件,我会执行以下操作:
<script type="text/javascript">
function element_hide(id) { document.getElementById(id).style.display = "none"}
function element_show(id) { document.getElementById(id).style.display = "block"}
</script>
<?php
$categories = array(
// Insert all categories here. If a new property comes along
// (e.g. "active/inactive") we can easily add it.
array("label" => "Smycken & Klockor", "id" => "nav_sub_juveler"),
array("label" => "Vuxen-plagg", "id" => "nav_sub_vuxen_plagg")
...
);
foreach ($categories as $category)
{
echo "if (category == '".$category["label"]."') ".
"element_show('".$category["id"]."');".
" else element_hide('".$category["id"]."');\n";
}
?>
这并不关心输出,但是在回显条件时可以使用一些 \n
和空格轻松美化输出。
关于php - 我有很多 "IF/ELSE"语句,我应该以不同的方式写吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2281818/