jQuery .inArray() 总是正确的? [英] jQuery .inArray() always true?
问题描述
我正在尝试使用 inarray 但它总是返回 true?有任何想法吗?(所有 li 都在显示)
I'm trying to use inarray but its always returning true? Any ideas? (all li's are showing)
$("#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 ) {
$.inArray()
方法返回0
基于项目的索引.如果没有项,则返回 -1
,if()
语句会将其视为 true
.
The $.inArray()
method returns the 0
based index of the item. If there's no item, it returns -1
, which the if()
statement will consider as true
.
来自文档:
因为 JavaScript 将 0 视为粗略等于 false(即 0 == false,但 0 !== false),如果我们检查数组中是否存在值,我们需要检查它是否不等于 (或大于) -1.
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.
<小时>
不要将两个值作为一个对象推送到数组中,只需使用一个或另一个,这样您就有了一个字符串数组,您可以从中构建一个多重选择器.
Instead of pushing both values into the array as an object, just use one or the other, so you have an Array of strings from which you can build a multiple selector.
一种方法是这样的:
// 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'];
结果选择器将如下所示:
The resulting selector will look like:
$( "#Army,#Aqua,#Bread" ).show();
这篇关于jQuery .inArray() 总是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!