使用 jQuery 用 JSON 数据填充 HTML

Nic*_*son 3 html javascript jquery json

我正在尝试在我的 HTML 中动态创建申请人列表。我有一个以 JSON 格式保存的申请人列表,我正在阅读。我有一个申请人“tile”的 HTML 模板,我读入、填充然后附加到每个申请人的页面。

我的模板:

<div>
   <div class="name"></div>
   <div class="age"></div>
   <div class="gender"></div>
   <div class="email"><i class="fa fa-envelope"></i></div>
</div>
Run Code Online (Sandbox Code Playgroud)

我的 JSON 数据:

{
  "applicants" : [
    {
      "name" : "John Smith",
      "email" : "email@gmail.com",
      "gender" : "Male",
      "age" : "22"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我的jQuery:

 $.get("applicants.json", function(json) {
     json.applicants.forEach(function(applicant) {
         var newApplicant = $(templates).find("#applicant").html();

         $(newApplicant).find(".name").append(applicant.name);
         $(newApplicant).find(".email").append(applicant.email);
         $(newApplicant).find(".gender").append(applicant.gender);
         $(newApplicant).find(".age").append(applicant.age);

         $(newApplicant).appendTo(".applicant-list");
     });
 });
Run Code Online (Sandbox Code Playgroud)

运行此代码后,我只是在没有 JSON 信息的情况下取回模板。

我试过console.log()在追加后放置一个,applicant.name但仍然没有改变newApplicant.

我尝试过的其他事情console.log($(newApplicant).find(".name").append(applicant.name).html());表明.name正在填充,但这些更改不会持续存在。

谁能看到我做错了什么?

谢谢。

Pra*_*man 5

我不确定这是否forEach是正确的。您可以使用 jQuery 的$.each函数在数组中循环,this并被称为当前迭代对象:

$.each(json.applicants, function () {

  var newApplicant = $("body").find("#applicant > div").clone();

  newApplicant.find(".name").append(this.name);
  newApplicant.find(".email").append(this.email);
  newApplicant.find(".gender").append(this.gender);
  newApplicant.find(".age").append(this.age);

  $(newApplicant).appendTo(".applicant-list");
});
Run Code Online (Sandbox Code Playgroud)

片段

$.each(json.applicants, function () {

  var newApplicant = $("body").find("#applicant > div").clone();

  newApplicant.find(".name").append(this.name);
  newApplicant.find(".email").append(this.email);
  newApplicant.find(".gender").append(this.gender);
  newApplicant.find(".age").append(this.age);

  $(newApplicant).appendTo(".applicant-list");
});
Run Code Online (Sandbox Code Playgroud)
$(function () {
  json = {
    "applicants" : [
      {
        "name" : "Nicholas Robinson",
        "email" : "ntrpilot@gmail.com",
        "gender" : "Male",
        "age" : "22"
      }
    ]
  };

  $.each(json.applicants, function () {

    var newApplicant = $("body").find("#applicant > div").clone();

    newApplicant.find(".name").append(this.name);
    newApplicant.find(".email").append(this.email);
    newApplicant.find(".gender").append(this.gender);
    newApplicant.find(".age").append(this.age);

    $(newApplicant).appendTo(".applicant-list");
  });
});
Run Code Online (Sandbox Code Playgroud)