为什么JS在某一行之后停止处理我的代码?

时间:2011-07-17 13:23:38

标签: javascript jquery

好吧,我现在已经超过这一天超过一天了。而且我确信解决起来非常简单。

下面的函数应该这样做:从php文件中获取一些发布数据(返回xml格式),成功处理数据以检查购物车中的商品是否已存在此项目,以防止它被存在以相同名称添加两次。因此,它遍历当前的项目列表并找到匹配项。如果找不到,它会添加该项目。如果存在,则需要进行操作以使用新金额更新该行。

由于某些奇怪的原因,我无法在匹配时立即执行代码。 if(match == true)只是没有做任何事情,即使console.log("index found present status: "+match);在控制台中返回true就好了几行。

那怎么可能呢?是否与范围有什么关系?

if(basket.fnGetData().length == 1) addToCart('window', 1);仅用于确保函数的第二次调用存在需要“合并”为一个的重复项。每次都可以点击网站上的内容。

    function addToCart (ueid, amount)
    {
    // you can remove the follow alert() call, typically this function would
    // scroll (through an #anchor or maybe tween/scroll with jQuery) down to
    // the area below the panorama tour and there display the user-interface
    // for buying/sponsoring items

    console.log("buy "+ueid+" "+amount+" times");
    var match = false;

    console.log("before ajax present status: "+match); //output: false

    //Get detailed info about this item
    iteminfo = jQuery.ajax(iteminfourl, { data: { "ueid": ueid }, type: "POST",
    success: 
        function(data) 
        {
            console.log("ajax success present status: "+match); //output: false
            totalprice = (amount * $(data).find('price').text());

            //first check if the item already exists in the table
            currentContents = basket.fnGetData();

            if(currentContents.length > 0)
            {
                for(index = 0; index <= currentContents.length; index++)
                {
                    if(currentContents[index][0] == ueid)
                    {
                        console.log("ueid and index are the same");

                        match = true;
                        var updateIndex = index;                    
                        console.log("index found present status: "+match); //output: true
                    }
                }
            }

            if(match == true)
            {
                //this never gets executed, even if match is set to true. 
                                //also console.logs just before the if statement are only 
                                //executed when match = false all the way...
                                console.log("item is present, update index "+updateIndex);
                //basket.fnUpdate()
            }
            else
            {           
                basket.fnAddData(
                [
                    ueid,
                    amount,
                    totalprice,
                    'X'
                ]
                );

                if(basket.fnGetData().length == 1)
                    addToCart('window', 1);
            }
        }
    }); 
}

1 个答案:

答案 0 :(得分:3)

for(index = 0; index <= currentContents.length; index++)

应该是

for(var index = 0; index < currentContents.length; index++)

密钥在循环表达式中使用<而不是<=。 我认为当你执行currentContents[1 too many][0]时,你的循环正在运行额外的时间并抛出TypeError。查看调试控制台是否打印出错误警告。