jQuery $ .each()仅返回Json对象中的第一个元素

ale*_*lex -1 javascript ajax each jquery json

我想从循环遍历Json对象(结果)的$ .each()函数动态填充#city div的内容.如何将对象中的所有元素放入#city div中?

在这种情况下创建和替换html元素的最佳方法是什么?(从每个功能)

我的代码:

<div id="city"></div>
Run Code Online (Sandbox Code Playgroud)


$.ajax({
        url: "/Home/GetCity",
        type: "GET",
        data: { county: County}
    })
    .done(function (result) {
        $.each(result, function (index, value) {
            console.log(this.CityName); //here it returns all the elements
           $('#city').html("<h4>" + this.CityName+ "</h4>"); //here it return only the first one

       });
    });
Run Code Online (Sandbox Code Playgroud)

Mar*_*que 6

您正在覆盖所有值,因为您正在使用"html"jquery函数.我建议使用append:

$('#city').empty().append("<h4>" + this.CityName+ "</h4>");
Run Code Online (Sandbox Code Playgroud)