0

我有一个函数,我试图检查一个值是否已经存在。然而,即使值存在,它仍然返回 -1。我试图让我的 if/else 语句工作,如果一个项目存在它“警报”,如果它不运行函数 addItem();

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

2 回答 2

1

这是因为detailIDanditemArr是函数的局部变量itemExists(),也是undefined您的if条件所在。

把它移到外面,应该修复它。

...
var detailID = $(this).attr('id'); 
var itemArr = [];
function itemExists() {
   ...
}
...
于 2013-04-11T16:04:57.740 回答
0

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

我不知道如何证明这一点,因为您没有提供任何示例输入。然而,在您调用关键字itemExists的方式中是/ ,并且可能是 results 。thisundefinedwindow$(this).attr('id')undefined

要解决这个问题,要么使用itemExists.call(this)或将 DOM 元素(甚至$(this)?)存储在局部变量中并使用它,或者甚至移出itemExists处理程序并使用显式参数调用它。

如果项目存在,我正在尝试让我的 if/else 语句正常工作……</p>

如您所见,返回的索引是-1. 这意味着要检查一个元素是否包含在数组中,您需要与 -1 进行比较,而不是将每个非零数转换为true

if (jQuery.inArray(detailID, itemArr) != -1)
于 2013-04-11T17:32:51.880 回答