【问题标题】:jQuery Click Function: Show Div Based on Previous Radio Button SelectionjQuery Click 功能:根据先前的单选按钮选择显示 div
【发布时间】:2014-10-02 14:58:34
【问题描述】:

我整天都在寻找答案,但似乎找不到任何可以解决我的具体问题的东西,所以就这样吧。

在问题表单中,我想使用 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

【问题讨论】:

  • jQuery(".hide").hide();

标签: javascript jquery css radio-button show


【解决方案1】:

如果您不想再次隐藏显示的 div,那么只需从“显示”的项目中删除“隐藏”类

这里是JSFiddle

下面是如何做到这一点的一个示例行:

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

【讨论】:

  • 这将是解决您问题的最简单/最快的方法。 +1 为简单起见。
  • 很好的答案和“.removeClass('hide')”也非常有用!非常感谢。
【解决方案2】:

删除所有

jQuery(".hide").hide();

(现在是fiddle

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 2011-02-16
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多