【问题标题】:Show/Hide Dropbox using Radio Button and JQuery使用单选按钮和 JQuery 显示/隐藏 Dropbox
【发布时间】:2015-04-15 17:44:32
【问题描述】:

这是我的 HTML:

<input type="radio" value="rural" id="rural" name="landtype" checked>Rural
<input type="radio" value="urban" id="urban" name="landtype" checked>Urban

<select id="budget1" class="dbox1">
                    <option value="9000">8000php-10000php</option>
                    <option value="13000">12000php-14000php</option>
                    <option value="17000">16000php-18000php</option>
                </select>

<select id="budget2" class="dbox2">
                    <option value="10000">9000php-11000php</option>
                    <option value="14000">12000php-15000php</option>
                    <option value="18000">17000php-19000php</option>
                </select>

这是我的 javascript 代码:

<script type="text/javascript">

    $(document).ready(function(){
                      $('input[type="radio"]').click(function(){
                           if($(this).attr("value")=="rural"){

                                document.getElementById("budget2").hide();
                                document.getElementById("budget1").show();

                           }
                           if($(this).attr("value")=="urban"){
                                document.getElementById("budget1").hide();
                                document.getElementById("budget2").show();
                           }
    });
    });

</script>

我想要的是,如果我单击“农村”单选按钮,“dbox2”将隐藏,然后“dbox1”将显示。 如果我单击“城市”单选按钮,“dbox1”将隐藏,然后“dbox2”将显示。

到目前为止,我得到的是来自“document.getElementById("budget1").hide();”行的“错误”,上面写着“未捕获的类型错误:未定义不是函数”

有什么办法吗?

【问题讨论】:

  • 该元素上没有 hide() 方法。您需要使用$('#budget1').hide() - 请参阅此链接以获取可能的解决方案:stackoverflow.com/questions/29633699/…
  • 另外,您可能希望将此处选择的事件click$('input[type="radio"]').click( ... 更改为事件change,这样它只会在值更改时发生,而不是在每次点击时发生。

标签: javascript jquery html radio-button show-hide


【解决方案1】:

如果您使用的是 jQuery,请使用它并更改该行:

document.getElementById("budget2").hide();
document.getElementById("budget1").show();

到:

$("#budget2").hide();
$("#budget1").show();

编辑:抱歉,我忘了添加 ID 选择器。

【讨论】:

  • $("budget2").hide(); $("budget1").show(); 这失败了。 @Red 需要像这样使用选择器语法:$("#budget2").hide(); $("#budget1").show();
【解决方案2】:

hide() 和 show() 是 jQuery 函数,这就是为什么会出现这些错误。使用 $() 获取这些元素,然后调用 hide 和 show。

【讨论】:

    【解决方案3】:
    $("#budget2").hide();
    
    
    $("#budget1").show();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多