首頁>Program>source

我正在尝試使用inarray但它总是返迴true? 有任何想法吗? (李的所有都在顯示)

$("#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();
    };
最新回復
  • 12天前
    1 #

    您需要執行以下操作:

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

    或者這个:

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

    $.inArray() 方法返迴 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.


    EDIT: 不必將两个值都作為一个物件推送到陣列中,而是使用一个或另一个,這樣您就可以使用一个字元串陣列来構建多个選擇器。

    一種方法是這樣的:

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

  • 12天前
    2 #

    ES6进行救援! 虽然不是jQuery,但我认為值得未来的讀者...

    ES6引入了 .includes() 就像您认為的那樣 應该工作:

    $.inArray
    

    Array.prototype.includes()

    const myArray = ["a", "b", "c"]; console.log(myArray.includes("a")) /* true */ console.log(myArray.includes("d")) /* false */

  • tsql:T-SQL計算移動平均值
  • 如何在R中訪問help / documentation rd源檔案?