2010-12-29 13 views
16

Sto provando a usare inarray ma è sempre vero che restituisce vero? Qualche idea? (Tutte Li stanno mostrando)jQuery .inArray() sempre vero?

$("#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(); 
    }; 

risposta

50

Hai bisogno di fare questo:

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

o questo:

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

The $.inArray() method restituisce l'indice in base 0 della voce. Se non ci sono articoli, restituisce -1, che la dichiarazione if() considererà come true.

Dalla documentazione:

Poiché JavaScript considera 0 come vagamente uguale a false, se stiamo controllando la presenza di valore all'interno dell'array (cioè 0 == false, ma 0 == false!) , dobbiamo controllare se non è uguale a (o maggiore di) -1.


EDIT: Invece di spingere entrambi i valori nella matrice come oggetto, basta utilizzare uno o l'altro, in modo da avere una matrice di stringhe da cui è possibile costruire un selettore multiplo.

Un modo è come questo:

// 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(); 

Se l'Array assomiglia:

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

Il selettore risultante sarà simile:

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

Hummm? ora nessuno di loro sta mostrando? –

+0

ecco l'elenco di selezione ... Blackberry –

+0

@Charles: questo perché la matrice' arrVals' non contiene ''Army'' o'' Aqua'', ma contiene invece un oggetto dove sia la 'chiave' o' valore' (non sono sicuro quale) ha la stringa che si desidera. – user113716

0

ES6 per il salvataggio! Non Anche se jQuery ho pensato che vale la pena di rispondere per i lettori futuri ...

ES6 introduce .includes() che funziona come si pensa $.inArray dovrebbe funzionare:

const myArray = ["a", "b", "c"]; 
 

 
console.log(myArray.includes("a")) /* true */ 
 
console.log(myArray.includes("d")) /* false */

Array.prototype.includes()

Problemi correlati