使用jquery从JSON数据生成动态html

Generating dynamic html from JSON data with jquery

本文关键字:动态 html 数据 jquery JSON 使用      更新时间:2023-09-26

我一直在谷歌上搜索并寻找动态生成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>'

使用Mustache或Handlebars之类的模板引擎。您可以将"胡子"注入到模板中,并在传递的数据中相应地命名它们。这样就不需要遍历新创建的HTML的DOM来注入值。