2013-04-11 49 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