繁体   English   中英

Javascript array.length为0,直到我发出警报()

[英]Javascript array.length is 0 until I do an alert()

我正在尝试编写一些基于Sharepoint WebServices getList响应构建html控件的javascript。 我将控件存储在一个数组中。 构建数组后,长度为0,直到我执行警报,然后它变为正确的数字。

var controls = [];

$(document).ready(function() {
    // Make call to WebServices to retrieve list data
    $().SPServices({
        operation:    "GetList",
        listName:     qs["list"],
        completefunc: parseList
    });

    console.log(controls.length);           // this outputs 0
    alert("This has to be here to work.");  // this has to be here, no idea why
    console.log(controls.length);           // this outputs 6
    for (var i=0; i<controls.length; i++) {
        controls[i].addControl();
    }
});

function parseList(xData,status) {
    $(xData.responseXML).find("Field").each(function() {
        if ($(this).attr("ID") && $(this).attr("SourceID") != "http://schemas.microsoft.com/sharepoint/v3") {
            if ($(this).attr("Type") == "Text") {
                controls.push(new Textbox(this));
            } else if ($(this).attr("Type") == "Choice" && $(this).attr("Format") == "Dropdown") {
                controls.push(new Dropdown(this));
            } else if ($(this).attr("Type") == "Choice" && $(this).attr("Format") == "RadioButtons") {
                controls.push(new RadioButtons(this));
            } else if ($(this).attr("Type") == "MultiChoice") {
                controls.push(new MultiChoice(this));
            } else if ($(this).attr("Type") == "Boolean") {
                controls.push(new Boolean(this));
            }
        }
    });
}

警报似乎是唯一使controls.length正常工作的东西。 我只能认为这是某种范围问题。 任何见解都表示赞赏。

这可能是由于这个异步代码

$().SPServices({
        operation:    "GetList",
        listName:     qs["list"],
        completefunc: parseList
});

警报暂时停止线程执行,以允许调用回调函数

所以试着移动这部分

console.log(controls.length);           // this outputs 6
for (var i=0; i<controls.length; i++) {
    controls[i].addControl();
}

进入parseList()函数

$().SPServices是一个异步函数。 在调用parseList之前,不会填充controls数组。 移动循环以将控件添加到parseList回调。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM