【问题标题】:jQuery option to show input disappears显示输入的jQuery选项消失了
【发布时间】:2013-10-12 09:31:54
【问题描述】:

我有这个简单的<select>,如果选择了“其他”选项,它应该会显示一个输入。但是,如果我打开/关闭选择,或选择任何其他选项,“其他”就会消失。

这就是我的意思:

<script type="text/javascript">
    $(document).ready(function(){
    var $milestones = $(".other"),
        $selector = $('#source');

    $selector.change(function() {
        var selected = $selector.find('option:selected').attr('class');

        $milestones.hide();
        $('#' + selected).show();
    });
});
</script>

下面是包含选择和隐藏 div 以显示输入的 HTML:

<div class="field text">
    <label>Where did you hear about us?</label>
    <select name="source" id="source">
        <option value="Facebook">Facebook</option>
        <option value="Twitter">Twitter</option>
        <option value="Other" class="other">Other</option>
    </select>
</div>
<div class="field text">
    <div id="other" class="hideme">
        <label>Sources:</label><input type="email">
    </div>
</div>

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    我猜你想在选择 option.other 时显示输入。所以这里是代码:

    $(document).ready(function(){    
        var $selector = $('#source');
    
        $selector.change(function() {
            var showOther = $('option.other').is(':selected');
            $('#other').toggle(showOther);
        });
    });
    

    为此,您应该从一开始就隐藏输入,让jQuery.toggle() 完成它的工作。

    .hideme {
        display: none;
    }
    

    http://jsfiddle.net/kWSrh/

    【讨论】:

      【解决方案2】:

      您隐藏了 .other 元素而不是输入框。看看这些变化。

      $(document).ready(function(){
        $('.hideme').hide();
        $selector = $('#source');
      
        $selector.change(function() {
          var selected = $selector.find('option:selected').attr('class');
      
          $('.hideme').hide();
          $('#' + selected).show();
        });
      });
      

      http://jsfiddle.net/sBw5X/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多