【问题标题】:Add array to conditional jQuery show/hide script将数组添加到条件 jQuery 显示/隐藏脚本
【发布时间】:2013-07-27 20:54:34
【问题描述】:

我正在使用带有 PHP 的 jQuery 脚本根据下拉选择有条件地显示/隐藏表单字段。
脚本是:

//Hide the field initially
        $("#hide1").hide();

        //Show the text field only when the third option is chosen - this doesn't
        $('#project-type').change(function() {
                if ($("#project-type").val() == "Value 1") {
                        $("#hide1").show();
                }
                else {
                        $("#hide1").hide();
                }
        });

我希望能够向if ($("#project-type").val() == "Value 1") 添加一个值数组,因此如果有五个值,我希望某个字段显示何时选择值 1 和 3 而不是其他值。我尝试了几种方法,但它们都导致所有值都显示隐藏字段。
任何帮助表示赞赏。

【问题讨论】:

    标签: php jquery arrays add


    【解决方案1】:

    jQuery inArray 应该可以完成这项工作;

    var val = $("#project-type").val(); // Project type value.
    
    var show = $.inArray(val, ['Value 1', 'Value 2', ...]) > -1 ? 'show' : 'hide'; // If the value is in the array, show value is 'show' otherwise it is 'hide'.
    
    $("#hide1")[show](); // Show or hide $('#hide1').
    

    【讨论】:

      【解决方案2】:

      有很多选择,一个简单的方法是将您的 if 更改为:

      if ($("#project-type").val() == "Value 1" || $("#project-type").val() == "Value 3")
      

      或:

      if (["Value 1", "Value 3"].indexOf($("#project-type").val()) != -1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-18
        • 1970-01-01
        相关资源
        最近更新 更多