簡體   English   中英

使用jQuery從JSON數據生成動態HTML

[英]Generating dynamic html from JSON data with jquery

我一直在進行大量的Google搜索,並尋找動態生成html的最佳方法。 我當前的解決方案遵循代碼段。 我的代碼的想法是從服務器獲取數據,然后使用返回的任務項數組構建動態列表內容。

我的問題是,肯定有更好,更冗長和更可維護的方式來執行此操作嗎?

 // returns an array of task objects from server $.post("/fetch", JSON.stringify({ "Sort": "tasksperuser" }), function(data) { // Generate a task line item in html before appending for each task object. $.each(data, function() { console.log($(this)); $("#taskBox").append(taskline); var tempkey = $(this)[0]['key']; $("#taskBox > p:last").attr("id", tempkey); if ($(this)[0]['completed'] == true) { $("#" + tempkey + " .taskCheckbox").prop('checked', true) .siblings('.task-title').css("text-decoration", "line-through"); } $("#" + tempkey + " .task-title").text($(this)[0]['title']); }) }, "json") .fail(function() { console.log("Tasks load per user from server failure."); }); var taskline = '<p id="" class="taskWrapper">' + '<input type="checkbox" class="taskCheckbox"/>' + '<span class="task-title"></span>' + '<button type="button" class="btn btn-default btn-xs taskDelete pull-right" aria-label="Left Align">' + ' <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' + '</button>' + '<button type="button" class="btn btn-default btn-xs pull-right" data-toggle="modal" data-target="#TaskModal" data-key="" aria-label="Left Align">' + ' <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>' + '</button>' + '</p>' 

使用諸如MoustacheHandlebars之類的模板引擎。 您可以在模板中注入“肌肉萎縮症”,並在傳遞的數據中相應地命名它們。 這樣就無需遍歷新創建的HTML的DOM來注入值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM