[英]Using JSON To Populate UL With jQuery
這是我的JSON數據
[
{"CountyId":2,"Name":"Snohomish","StateId":1,"State":null,"Plans":null},
{"CountyId":1,"Name":"Whatcom","StateId":1,"State":null,"Plans":null}
]
我正在嘗試使用此數據在我的網頁上填充UL。
function loadSavedCounties() {
$.post("/Plans/GetPlanCounties/",
{ planId: $("#PlanId").val() },
function (data) {
populateSavedCounties($("#SavedCounties"), data);
}
);
}
function populateSavedCounties(select, data) {
select.html('');
var items = [];
$.each(data, function (id, option) {
items.push('<li>' + option.Name + '</li>');
});
select.append(items.join(''));
}
我知道我已成功調用loadSavedQueries()
因為我的UL已被select.html('')
調用清除。 但沒有任何物品被放回UL。
在明顯的修復和更改不起作用之后,我發現控制器中沒有拋出錯誤的問題,但基本上是返回空的JSON對象。 一旦我發現了這一點,數據開始流下來,建議的更改就可以了。
您可以在最后設置UL的html - 無需先清除它:
function populateSavedCounties(select, data) {
var items = [];
$.each(data, function (id, option) {
items.push('<li>' + option.Name + '</li>');
});
select.html(items.join(''));
}
這很容易,我先寫代碼,然后再回去解釋一下。
腳本
// You obviously know how to use .post
$.post("/Plans/GetPlanCounties/", { planId: $("#PlanId").val() }, function(data) {
// out of simplicity, i did not create a seperate function, however you seem to know how to move functions around
// below of course i simply assign a variable for reuse to the element you want
var $this = $("#SavedCounties").empty();
// instead of .each, I went on the premise that your data is returned exactly as stated above,
// in which case, a simple old school for statement is easiest
for (x in data) {
// this is real simple, the first part creates a jQuery object of a List Element
// the text part adds the text too it (aka, html you were wanting)
// the last part appends the Li to the END of the UL
$("<li />").text(data[x].Name).appendTo($this);
};
});
沒有評論的最終結果非常簡短和甜蜜
$.post("/Plans/GetPlanCounties/", { planId: $("#PlanId").val() }, function(data) {
var $this = $("#SavedCounties").empty();
for (x in data) {
$("<li />").text(data[x].Name).appendTo($this);
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.