2014-06-25 61 views
0

我正在嘗試從原本僅用於一個的代碼創建4個圖庫。我承認我幾乎不知道JavaScript是一個自學成才的初學者。我遇到的問題是,當我向字符串添加多個「照片」時,所有4個畫廊都停止工作。我毫不懷疑這是一個簡單的語法修復,但我一直無法找到它,也許我甚至不知道做足夠的搜索,但我希望這裏的某個人能夠提供幫助。JavaScript multistring if function

function showPanel(el){ 
    $('section').slideUp('fast'); 
    $('section#'+el).slideDown(1500); 

    if (el == 'photos' && 'graphics' && 'web' && 'books') { 
     $('a.works').fancybox({'titlePosition' : 'inside'}); 
     $('a.works.iframe').fancybox({ 'type' : 'iframe', 'titlePosition' : 'inside'}) 

     $('#da-thumbs > article').hoverdir(); 

     $('#filter a').on('click', function(){ 
      $('#filter a').removeClass('active'); 
      $(this).addClass('active'); 
     }); 


     filter(); 

    } else if(el == 'about') { 

     $('.about .avatar').remove(); 
     $('.home .avatar').clone().appendTo('.about #avatar'); 

     $('.chart').easyPieChart({ 
      animate : 500, 

      // ---------------------------- 
      // Custom your chart color here 
      // ---------------------------- 

      barColor : '#eb5b5e', 
      size : 110 
     }); 
    } else if(el == 'contact') { 
     $('.gmap').mobileGmap(); 
    } 

} 
+0

首先,你將要使用或者替代和 – Bergi

+0

對於'&&'和''||運營商需要充分的表達式:'如果(條件1 &&條件2 && ...)'這是檢查'el =='photos'' true,然後就是字符串''graphics''也是如此,等等。只是一個字符串總是如此。你會希望使用'||',並確保每次'el =='photos'||都聲明'e1' el =='圖形'|| ...「'。 –

+0

我已經嘗試了所有的建議,但它似乎仍然沒有工作。非常感謝你的幫助! – datieray

回答

1

if else塊,你需要傳遞一個bool值。否則它將無法工作。所以,當你傳遞一個值時。它必須是這樣的

if (el == 'photos' && 'graphics' && 'web' && 'books') { 

這意味着,如果el變量等於照片和圖形,如果現在編譯器不會明白你要告訴它什麼。 String != Bool

條件改變到這個

if (el == 'photos' && el == 'graphics' && el == 'web' && el == 'books') { 

這將各條件改變到布爾(真或假),然後將執行代碼塊。如果el等於照片圖形網絡和書籍。

但是,一個變量不能包含4個值。

所以,你可以把它寫成

if (el == 'photos' || el == 'graphics' || el == 'web' || el == 'books') { 

它會檢查是否有el任何提到的那些中的價值。

+0

'if'陳述是矛盾的,並且總是'false'。可能不是用戶想要的。 –

+0

@Juhana這次我寫的是同樣的東西! :)看到我的答案和白金,我已經編輯它。 –

3

使用switch語句。在我的選擇中,它更易於閱讀。

switch (el) { 
    case 'photos': 
    case 'graphics': 
    case 'web': 
    case 'books': 
    //do stuff 
    break; 
    case 'about': 
    //do stuff 
    break; 
    case 'contact': 
    //do stuff 
    break; 
} 
1

嘗試

if ((el == 'photos') || (el == 'graphics') || (el == 'web') || (el == 'books')) {