【发布时间】:2014-09-24 21:07:29
【问题描述】:
我想从循环通过 Json 对象(结果)的 $.each() 函数动态填充#city div 的内容。如何从对象中获取所有元素并将它们放入#city div?
在这种情况下创建和替换 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
});
});
【问题讨论】:
-
我建议使用 for 循环而不是 each。
-
您可能希望发布示例 JSON 以确保看起来不错。您还需要使用
append而不是html,因为html会完全替换内容。 -
@Armen,有什么特别的原因吗?
-
你的问题是.html,现在我明白了,每次你替换整个html时,最后都会显示最后一个项目。
-
@Armen 但问题指出它返回第一个元素,而不是最后一个。
标签: javascript jquery ajax json each