2014-10-02 52 views
0

我一直在尋找一個答案整天,但似乎無法找到任何有助於我的具體問題,所以在這裏。jQuery點擊功能:根據以前的單選按鈕選擇顯示Div

在問題形式中,我想使用jQuery click()函數顯示基於單選按鈕選擇的隱藏div。但是在觸發第二次click()事件後,上一次選擇中顯示的div將被遺忘,並返回到隱藏狀態。

下面是一個例子代碼:

jQuery(document).ready(function(){ 
 
    jQuery('input[type="radio"]').click(function(){ 
 
      if(jQuery(this).attr("value")=="answer1"){ 
 
       jQuery(".hide").hide(); 
 
       jQuery(".answer1").show(); 
 
       jQuery(".answer1and2").show(); 
 
      }                      
 
      if(jQuery(this).attr("value")=="answer2"){ 
 
       jQuery(".hide").hide(); 
 
       jQuery(".answer2").show(); 
 
       jQuery(".answer1and2").show(); 
 
      } 
 
      if(jQuery(this).attr("value")=="answer3"){ 
 
       jQuery(".hide").hide(); 
 
       jQuery(".answer1and2").show(); 
 
       jQuery(".answer3").show(); 
 
      } 
 
     }); 
 
    });
.hide { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> 
 

 
<h1>Question 1</h1> 
 
<input type="radio" name="question1" value="answer1"> 
 
Answer 1 
 
<input type="radio" name="question1" value="answer2"> 
 
Answer 2 
 
    
 
<div class="answer1 hide"> 
 
<p>Answer 1 is Apple</p> 
 
</div> 
 

 
<div class="answer2 hide"> 
 
<p>Answer 2 is Mango</p> 
 
</div> 
 
    
 
<div class="answer1and2 hide"> 
 
<h1>Question 2</h1> 
 
<input type="radio" name="question2" value="answer3"> 
 
Any answer 
 
<input type="radio" name="question2" value="answer3"> 
 
Any answer 
 
</div> 
 

 
<div class="answer3 hide"> 
 
<p>Did you choose Apple or Mango?</p> 
 
</div>

我如何能留住恰好是第一選擇後顯示的答案嗎?

JSFiddle code here

+0

jQuery的隱藏()( 「隱藏」)。; <=該行隱藏所有具有「隱藏」類的div。你爲什麼要隱藏它們?他們不是已經隱藏了嗎?你的css中定義了.hide類嗎? – jevgenig 2014-10-02 15:01:06

回答

1

如果你不想顯示的div被再次隱藏起來,然後就去掉「隱藏」類從「出」的項目你

這裏是JSFiddle

而且這裏是一個示例如何做到這一點:

  jQuery(".answer1").show().removeClass('hide'); 
+0

這將是解決您的問題的最簡單/最快捷的方法。爲簡單起見+1。 – 2014-10-02 15:05:01

+0

好的答案和「.removeClass('hide')」原來也非常有用!非常感謝。 – chiappa 2014-10-02 15:36:13