2013-04-11 50 views
0

我有一個函數,我試圖檢查一個值是否已經存在。但是,即使存在值,它仍然返回-1。我試圖讓我的if/else語句工作,如果一個項目存在它「警報」,如果它不運行函數addItem();jQuery .inArray If/Else Always Returning -1

$(".detail-view button").on("click", function() { 
    itemExists(); 

    function itemExists() { 
     var detailID = $(this).attr('id'); 
     var itemArr = []; 
     $("input#lunchorder_item_entry_id").each(function (index) { 
      var lunchItemID = $(this).val(); 

      itemArr.push(lunchItemID); 
     }); 

     addItem(); 

     alert(jQuery.inArray(detailID, itemArr)); 

     /* 
     if (jQuery.inArray(detailID, itemArr)) { 
      alert("You have already added this item. If you want to change item details, please remove the item and re-add it to your cart. Thank You!"); 
     } else { 
      // the element is not in the array 
      addItem(); 
     } */ 

     console.log(itemArr); 
    } 
+1

檢查瓦爾的範圍。 – j08691 2013-04-11 16:03:44

+0

@ j08691我不確定我明白你的意思,我對jQuery相當陌生。 – philecker 2013-04-11 16:38:21

+0

'addItem'做什麼? – Bergi 2013-04-11 17:33:35

回答

1

這是因爲detailIDitemArr是局部的功能itemExists(),是undefined您的if條件。

將它移到外面,應該修復它。

... 
var detailID = $(this).attr('id'); 
var itemArr = []; 
function itemExists() { 
    ... 
} 
... 
+0

如果我將這些變量移到函數之外,我會得到'不能調用'undefined'的方法' – philecker 2013-04-11 16:30:36

+0

其實,沒有。我討厭錯誤的縮進,但:-) – Bergi 2013-04-11 17:26:46

+0

你告訴我,這不是我所得到的?而我的if/else在該函數內。 – philecker 2013-04-11 17:50:10

0

然而,即使存在價值它仍然返回-1

我不知道如何來證明,因爲你沒有提供任何樣品的輸入。然而,以您撥打itemExists的方式,this keywordundefined/window$(this).attr('id')可能結果undefined

爲了解決這個問題,要麼使用itemExists.call(this)或存儲的DOM元素(甚至$(this)?)在一個局部變量和使用,甚至是移動itemExists處理程序外,並有明確的參數調用它。

我試圖讓我的if/else語句的工作,如果一個項目存在...

正如你注意到沒有,返回的索引是-1。這意味着,檢查元素是否包含在數組中,您將需要比較反對-1,每一個非零數字無法投射到true

if (jQuery.inArray(detailID, itemArr) != -1) 
+0

樣品輸入'var itemArr = [「7267」,「7799」,「8888」];'。 – philecker 2013-04-11 17:50:48

+0

好的,謝謝。然後請'console.log(detailID)'並且在這裏發佈。 – Bergi 2013-04-11 17:53:49

+0

謝謝,但techfoobar的解決方案爲我工作。 – philecker 2013-04-11 18:05:49