可能存在Javascript作用域问题

Javascript Scope Issue Possibly

本文关键字:作用域 问题 Javascript 存在      更新时间:2023-09-26

我的变量"html"出现问题。我认为我的作用域是正确的,但当我运行这段代码时,会发生一些奇怪的事情。"html"变量的第一个警报会产生一个空白结果,然后我用同一个"html"参数填充我的选择列表,它就工作了,然后我再次警报"html",选项就会显示出来。

如果我删除这两个警报,则列表不会弹出

function populateMakes(years)
{
    var makes = new Array();
    var html = "";
    $.each(years, function () {
        var uri = "/api/make?year=" + this;
        $.getJSON(uri, function (data) {             
            $.each(data, function () {
                if (jQuery.inArray(this.Id, makes) == -1)//makes not contain make
                {
                    makes.push(this.Id);
                    html += "<option value=" + this.Id + ">" + this.Value + "</option>";
                }
            });
        });
    });
    alert(html);
    $("#Make").html(html);
    alert(html);
    $("#MakeSection").removeClass("hidden");     

};

文档就绪脚本

$(document).ready(function () {
    populateYears();
    $("#Year").change(function () {
        $("#MakeSection").addClass('hidden');
        $("#ModelSection").addClass('hidden');
        $("#SubModelSection").addClass('hidden');
        populateMakes($("#Year").val());
    });
    $("#Make").change(function () {
        $("#ModelSection").addClass('hidden');
        $("#SubModelSection").addClass('hidden');
        populateModels($("#Year").val(), $("#Make").val());
    });
    $("#Model").change(function () {
        $("#SubModelSection").addClass('hidden');
       //
    });
    $("#Clear").click(function () {
        $("#YearSection").addClass('hidden');
        $("#MakeSection").addClass('hidden');
        $("#ModelSection").addClass('hidden');
        $("#SubModelSection").addClass('hidden');
        populateYears();
    })
});

.getJSON是异步的,我忽略了时间。我需要添加.done回调并在那里设置输出。剧本根本还没写完。

 $.getJSON(uri, function (data) {
            $.each(data, function () {
                if (jQuery.inArray(this.Id, makes) == -1)//makes not contain make
                {
                    makes.push(this.Id);
                    html += "<option value=" + this.Id + ">" + this.Value + "</option>";
                }
            });
        }).done(function () {
            $("#Make").html(html);
            $("#MakeSection").removeClass("hidden");
        });

我也没有在问题中发布的代码的事件处理程序中发送数组。我先解决了。