繁体   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