2017-03-12 102 views
0

因此,我創建了幾個h2標籤,並將它們放置在一個列表中,它們都是可點擊的,點擊時它們會顯示div中的內容。這很棒,但我希望以前的內容消失,並由新內容取代。根據按鈕選擇更改div中的內容

下面是按鈕的樣子;

<div id="h2List">  
     <h2 id="reveal1">Who are the main characters?</h2> 

     <h2 id="reveal2">The action takes place on</h2> 

     <h2 id="reveal3">Space crafts include</h2> 

     <h2 id="reveal4">What are those things??</h2> 

     <h2 id="reveal5">When they're not flying their driving</h2> 
    </div>  

這是持有內容的div;

<div id="h2Reveal"> 
       <ul class="hidden" id="listOfCharacters"> 
       </ul> 
       <ul class="hidden" id="listOfPlanets"> 
       </ul> 
       <ul class="hidden" id="spaceStuff"> 
       </ul> 
       <ul class="hidden" id="things"> 
       </ul> 
       <ul class="hidden" id="drive"> 
       </ul> 
      </div> 

最後,這是我用來切換第二個div中的信息列表的jQuery;

$("#reveal1").on("click", function() { 
      $("#listOfCharacters").toggle(); 
     } 
    ); 

    $("#reveal2").on("click", function() { 
      $("#listOfPlanets").toggle(); 
     } 
    ); 
    $("#reveal3").on("click", function() { 
      $("#spaceStuff").toggle(); 
     } 
    ); 
    $("#reveal4").on("click", function() { 
      $("#things").toggle(); 
     } 
    ); 
    $("#reveal5").on("click", function() { 
      $("#drive").toggle(); 
     } 
    ); 

我希望這是有道理的。

回答

0

您可能需要使用toggleClass

$("#reveal1").on("click", function() { 
      $("#listOfCharacters").toggleClass('hidden'); 
     } 
    ); 

    $("#reveal2").on("click", function() { 
      $("#listOfPlanets").toggleClass('hidden'); 
     } 
    ); 
    $("#reveal3").on("click", function() { 
      $("#spaceStuff").toggleClass('hidden'); 
     } 
    ); 
    $("#reveal4").on("click", function() { 
      $("#things").toggleClass('hidden'); 
     } 
    ); 
    $("#reveal5").on("click", function() { 
      $("#drive").toggleClass('hidden'); 
     } 
    ); 
+0

這樣做的工作,但它似乎就像我的代碼一樣。當點擊時顯示與h2標籤相關聯的列表,並且當第二次點擊時也隱藏關聯列表。我試圖做的就像當揭示1被點擊時顯示與它相關的列表。然後說人點擊揭示5,我想隱藏先前顯示的列表,並將其替換爲與揭示5相關聯的那個。我實現了兩個建議的代碼塊,它們都工作,但它們與我原來所做的一樣編碼。 –

0

我同意使用toggleClass,但你可以將其擰緊了一下,從源ID到目標中引入映射提高可維護性。

var mapping = { 
    "reveal1": "#listOfCharacters", 
    "reveal2": "#listOfPlanets", 
    "reveal3": "#spaceStuff", 
    "reveal4": "#things", 
    "reveal5": "#drive" 
}; 

$("h2").on("click", function(event) { 
    $(mapping[event.target.id]).toggleClass('hidden'); 
}); 
相關問題