简体   繁体   English

使用jQuery从JSON数据生成动态HTML

[英]Generating dynamic html from JSON data with jquery

I've been doing a lot of googling and looking for the best way to dynamically generate html. 我一直在进行大量的Google搜索,并寻找动态生成html的最佳方法。 My current solution follows in code snippets. 我当前的解决方案遵循代码段。 The idea of my code is to grab data from the server and then use the returned array of task items to build dynamic list content. 我的代码的想法是从服务器获取数据,然后使用返回的任务项数组构建动态列表内容。

My question is, surely there is a better, less verbose and more maintainable way of doing this? 我的问题是,肯定有更好,更冗长和更可维护的方式来执行此操作吗?

 // 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>' 

Use a templating engine like Mustache or Handlebars . 使用诸如MoustacheHandlebars之类的模板引擎。 You can inject "mustaches" into the template and name them accordingly in the passed data. 您可以在模板中注入“肌肉萎缩症”,并在传递的数据中相应地命名它们。 This removes the need to traverse the DOM of your newly created HTML to inject values. 这样就无需遍历新创建的HTML的DOM来注入值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM