jQuery .inArray()总是真的吗?

我试图使用inarray但它总是返回真的?有任何想法吗? (所有李的显示)
$("#select-by-color-list li").hide();

// get the select
var $dd = $('#product-variants-option-0');

if ($dd.length > 0) { // make sure we found the select we were looking for

    // save the selected value
    var selectedVal = $dd.val();

    // get the options and loop through them
    var $options = $('option',$dd);
    var arrVals = [];
    $options.each(function(){
        // push each option value and text into an array
        arrVals.push({
            val: $(this).val(),text: $(this).text()
        });
    });




};

//This is where it is returning true...


if($.inArray('Aqua',arrVals)) {
    $("#select-by-color-list li#aqua").show();
    };
    if($.inArray('Army',arrVals)) {
    $("#select-by-color-list li#army").show();
    };

解决方法

你需要这样做:
if( $.inArray('Aqua',arrVals) > -1 ) {

或这个:

if( $.inArray('Aqua',arrVals) !== -1 ) {

The $.inArray() method返回项目的0的索引。如果没有项目,则返回-1,if()语句将被视为true。

从文档:

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false,but 0 !== false),if we’re checking for the presence of value within array,we need to check if it’s not equal to (or greater than) -1.

编辑:而不是将这两个值作为对象推送到数组中,只需使用一个或另一个,因此您可以使用一个字符串数组,从中可以构建多个选择器。

一种方式是这样的:

// Create an Array from the "value" or "text" of the select options
var arrVals = $.map( $dd[0].options,function( opt,i ){
    return opt.value || opt.text;
});

  // Build a multiple selector by doing a join() on the Array.
$( "#" + arrVals.join(',#') ).show();

如果数组看起来像:

['Army','Aqua','Bread'];

结果选择器将如下所示:

$( "#Army,#Aqua,#Bread" ).show();

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...