【问题标题】:Show div when radio button selected选择单选按钮时显示 div
【发布时间】:2014-02-06 00:49:34
【问题描述】:

我是 javascript 和 jQuery 的新手。 在我的 html 中有 2 个单选按钮和一个 div。如果我检查第一个单选按钮,我想显示该 div,否则我希望它被隐藏

so: 如果选中单选按钮#watch-me --> div #show-me 可见。 如果单选按钮#watch-me 未选中(既未选中也未选中第二个)--> div #show-me 被隐藏。

这是我目前所拥有的。

 <form id='form-id'>
<input id='watch-me' name='test' type='radio' /> Show Div<br />
<input name='test' type='radio' /><br />
<input name='test' type='radio' />
 </form>
 <div id='show-me' style='display:none'>Hello</div>

和 JS:

 $(document).ready(function () { 
$("#watch-me").click(function() {
 $("#show-me:hidden").show('slow');
 });
 $("#watch-me").click(function(){
 if($('watch-me').prop('checked')===false) {
    $('#show-me').hide();}
    });
});

我应该如何更改我的脚本来实现这一点?

【问题讨论】:

    标签: javascript jquery html css radio-button


    【解决方案1】:

    我会这样处理:

    $(document).ready(function() {
       $('input[type="radio"]').click(function() {
           if($(this).attr('id') == 'watch-me') {
                $('#show-me').show();           
           }
    
           else {
                $('#show-me').hide();   
           }
       });
    });
    

    【讨论】:

    • 我想你可以像这样很快做到; $('input[type="radio"]#watch-me').click(fun...
    • 如果默认选中单选按钮会怎样
    【解决方案2】:

    输入元素应该有值属性。添加它们并使用它:

    $("input[name='test']").click(function () {
        $('#show-me').css('display', ($(this).val() === 'a') ? 'block':'none');
    });
    

    jsFiddle example

    【讨论】:

      【解决方案3】:
      $('input[name=test]').click(function () {
          if (this.id == "watch-me") {
              $("#show-me").show('slow');
          } else {
              $("#show-me").hide('slow');
          }
      });
      

      http://jsfiddle.net/2SsAk/2/

      【讨论】:

        【解决方案4】:
         $('input[type="radio"]').change(function(){
              if($("input[name='group']:checked")){
              $(div).show();
            }
          });
        

        【讨论】:

        • 单独的代码块并不能提供好的答案。请添加解释(为什么它解决了问题,错误在哪里等等......)
        【解决方案5】:
        var switchData = $('#show-me');
        switchData.hide();
        $('input[type="radio"]').change(function(){ var inputData = $(this).attr("value");if(inputData == 'b') { switchData.show();}else{switchData.hide();}});
        

        JSFIDDLE

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-08-19
          • 2011-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-02-27
          • 1970-01-01
          相关资源
          最近更新 更多