2013-02-21 30 views
0

我有以下代碼..jQuery的多個動作之一,如果

function showNext(opt) { 
     takeAway(); 
     if(opt == "Picked Up") $("#pickedup").css("display", ""); 
     if(opt == "Bus to alternate") $("#altad2").css("display", ""); 
     if(opt == "Walk to alternate") $("#altad1").css("display", ""); 
    } 


function takeAway(){ 
    $("#pickedup").css("display", "none"); 
    $("#altad2").css("display", "none"); 
    $("#altad1").css("display", "none"); 
} 

在如果有人選擇公交車交替或步行交替將顯示altad2和altad1​​分別

這種情況下,但是,這並不是我想要什麼..

我想如果有人選擇公共汽車來替代它顯示altad2和altad1​​,如果有人要選擇步行替代它相同。

有一種簡單的方法來做到像

if(opt == "Bus to alternate") $("#altad2").css("display", "") and $("#altad1").css("display", ""); 
    if(opt == "Walk to alternate") $("#altad1").css("display", "") and $("#altad2").css("display", ""); 

回答

1

更好的方法是創造一個地圖,它會減少代碼的大小,並獲得更快。

function showNext(opt) { 
     takeAway() 

     var optMap={ 
      "Picked Up":"#pickedup", 
      "Bus to alternate":"#altad2,#altad1", 
      "Walk to alternate":"#altad2,#altad1", 
       } 
      $(optMap[opt]).css("display","") ;  

} 
function takeAway(){ 
    $("#pickedup,#altad2,#altad1").css("display", "none"); 
} 

將所有id保留在一個選擇器中,以逗號分隔。在這個它只會創建一個jQuery對象。

1

你可以嘗試這樣的事情:

if(opt == "Bus to alternate" || opt == "Walk to alternate"){ 
    $('[id^="altad"]').css("display", ""); 
} 
+0

這取決於是否有任何其他id也被命名爲「altad」,但這是最好的解決方案。 +1 – user1428716 2013-02-21 18:03:55

0

試試這個:

function showNext(opt) { 
takeAway(); 

if(opt == "Picked Up") $("#pickedup").css("display", ""); 
if(opt == "Bus to alternate") 
{ 
$("#altad2").css("display", ""); 
$("#altad1").css("display", ""); 
} 
if(opt == "Walk to alternate") 
{ 
$("#altad2").css("display", ""); 
$("#altad1").css("display", ""); 

} 


} 

Saludos;)