jQuery inArray 不起作用

jQuery inArray not working

本文关键字:不起作用 inArray jQuery      更新时间:2023-09-26

在我的验证中,必填字段可以更改。 我有一个必需的输入 ID 数组(必需)。 如果数组包含字符串"All",则需要所有输入。

我正在尝试使用 JQuery.inArray() 来确定是否需要。

function getIfRequired(id){
    console.log("id: "+id);
    console.log(required);
    console.log("inarray: "+jQuery.inArray(required, 'All'));
    if (jQuery.inArray(required, 'All') > -1){ return true; }
    else if(jQuery.inArray(required, id) != -1){ return true; }
    else{ return false; }
}

但它一直返回"-1"(未找到)。

以下是示例日志输出:

id: clientname
["clientname", "sourceid", "clientcountry","clienttown", "clienttownid", "typeoflaw"] 
inarray: -1 
id: clientname
["All"] 
inarray: -1 

为什么它不起作用?

你已经转置了你的值和数组参数,例如:

jQuery.inArray('All', required);

你叫错了jQuery.inArray.首先是值,然后是数组

见 http://api.jquery.com/jQuery.inArray/

jQuery.inArray('All', required);

而不是

jQuery.inArray(required, 'All');

因为在All中找不到required

你会写如下

 console.log("inarray: "+jQuery.inArray('All', required));

参考