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

jQuery $.each() returns only the first element from a Json object

本文关键字:对象 Json 第一个 元素 返回 each jQuery      更新时间:2023-09-26

我想通过$.each()函数动态地填充#citydiv的内容,该函数循环一个Json对象(result)。如何从对象中获取所有元素并将它们放在#citydiv中?

在这种情况下,创建和替换html元素的最佳方法是什么?(从每个函数中) 我的代码:



<div id="city"></div>


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

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

$('#city').empty().append("<h4>" + this.CityName+ "</h4>");