将数组添加到条件jQuery显示/隐藏脚本中


Add array to conditional jQuery show/hide script

我使用带有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时显示某个字段,而不显示其他字段。我尝试了一些方法,但它们都会导致所有值显示隐藏字段
感谢您的帮助。

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').

有很多选项,一个简单的选项是将if更改为:

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

或:

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