2016-12-15 50 views
0

我對編碼比較陌生,而且我很喜歡手風琴風格的設備我正在努力。爲什麼這個jQuery顯示&隱藏腳本不能按預期工作?

這個想法是有4個div元素和下面他們另一個div。當點擊4個div中的一個時,相關文本將顯示在框中;點擊另一個,第一個div的文本消失,並改變到另一個。點擊同樣的方塊,盒子就消失了。

我的遊戲計劃:爲所有應該隱藏的元素分配相同的類,並將其隱藏在網站上;當單擊div時,只顯示具有相應ID的元素。

目前,我堅持讓它只用一個div工作,我不知道爲什麼。如果你能告訴我問題在哪裏,我將不勝感激。因此

我的代碼遠(現在只有2 div的,使這個更簡潔):

HTML:

<div class="expander" id="first-p">Click this text to see the one below.</div> 
<div class="expander" id="second-p">Another clickable div.</div> 
<div class="concealed" id="concealed-first-p">This is the hidden text.</div> 
<div class="concealed" id="concealed-second-p">This is another hidden text.</div> 

JQUERY:

$(document).ready(function() { 
    $(".concealed").hide();    //hide all elements with class .concealed after site launch 

    $(".expander").click(function(){    //A div which triggers the displaying of the hidden stuff is clicked 


/* If the hidden div is already displayed, hide it instead and call it a day */ 

      if (clickedElement == $(this).attr("id")) { 
       alert ("hide div again"); 
       $("#expandingElement").hide(); 
      } 

/* Show the hidden div */ 

else { 
      $("#expandingElement").hide();    // hide any div that might already be displayed 
      var clickedElement = $(this).attr("id");   // get the ID of the clicked element so we know which correlating one to display afterwards 
      var expandingElement = "concealed-" + clickedElement;   // construct the ID of the element to display 
      alert("Name of expandingElement ID is " + expandingElement);    // this is just an alert so I know the variable was constructed correctly 
      $("#expandingElement").show();    // show the div 
      } 
     }); 
    }); 

到目前爲止,代碼工作起來直到警報顯示正確的變量名稱,但該div後來不顯示。你能告訴我我做錯了什麼嗎?

另外,我想有更簡單的方法來做到這一點,我很樂意在這件事上得到任何幫助。但最重要的是,我想知道爲什麼代碼無法按預期工作。

+1

你的哪個'html'的部分有''id' expandElement' – 2016-12-15 12:01:32

回答

1

好像你已經搞砸了選擇:

您的div都不具有ID「expandingElement」但你打電話

$("#expandingElement").hide() 

此嘗試應用隱藏()與元素ID expandingElement。但是你想使用名爲expandingElement的變量。所以,你需要做的是CONCAT這兩個正確:

$("#"+expandingElement).hide() 
+0

感謝您的詳細,新手友好的解釋! –

+0

不客氣。 –

+0

我在看到你和桑迪的回答後立即提出了投票,但由於該網站通知我「記錄了名聲低於15的人的投票,但不更改公開顯示的帖子分數」:/ –

0

您在「」使用ID。所以它被視爲string。 你應該使用這樣:

$("#" + expandingElement).show();

0

如果我是正確的它似乎是你正在尋找類似的Boostrap's Tabs

你失敗的東西是: $( 「#expandingElement」)。顯示隱藏(); (「#」+ expandingElement).show()/ hide();();();}}

expandingElement是一個變量,所以如果你在btwn中插入它,它就會變成一個字符串。

總之:

$(document).ready(function() { 
    $(".concealed").hide();  

    $(".expander").click(function(){    
     $(".concealed").hide(); 
     var clickedElement = $(this).attr("id"); 

     var expandingElement = "concealed-" + clickedElement;    

     $("#"+expandingElement).show();  

     }); 
    }); 
相關問題