gpt4 book ai didi

jQuery .inArray() 总是 true?

转载 作者:行者123 更新时间:2023-12-03 21:49:27 26 4
gpt4 key购买 nike

我正在尝试使用 inarray 但它总是返回 true?有任何想法吗? (所有 li 均已显示)

$("#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 的项目索引。如果没有项目,则返回 -1if() 语句会将其视为 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();

关于jQuery .inArray() 总是 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4558086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com