Div被克隆多次而不是所需的数量

时间:2019-04-07 16:02:46

标签: javascript jquery json methods clone

我有一些JSON data that contains four sections,并且我希望根据有多少部分来克隆html div。因此,如果我的JSON中有100个部分,则div应该被克隆100次。

我的div被克隆,并且JSON数据被附加到每个div,但是问题是div被克隆了不止一次。第一个JSON部分被克隆了4x,第二个被克隆一个3倍,第三个3倍,依此类推。这里有一种模式,但我不确定为什么会发生。

JSON

JS代码段:

import $ from 'jquery';
import jsonData from "./test.json";

let onlyTitles = jsonData.d.results.filter(result => result.Title !== "");

onlyTitles.forEach(title => {
  let $clonedDiv = $("#template").clone();
  $clonedDiv.removeAttr("id");

  $clonedDiv.find("#filledRowBody").append(`<td>${title.Title}</td><td>${title.Role}</td><td>${title.Office}</td><td>${title.IsActive}</td>`);
  $clonedDiv.find("#filledRowBody").removeAttr("id");
  $("#titleBody").append($clonedDiv);
})

HTML片段:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="template" class="col-6">

  <h3 id="display-form-job-title"></h3>

  <div class="button-group">
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Edit Form</button>

    <!-- Button trigger PDF -->
    <button type="button" class="btn btn-secondary" id="pdf-trigger" data-toggle="" data-target="#pdfprint">Save as PDF</button>
  </div>
  <hr>
  <h4>Hiring Goals:</h4>

  <div class="col-12">
    <table class="table order-list" id="hiring-goals-table">

      <thead>
        <tr>
          <td>Number of Hires</td>
        </tr>
      </thead>

      <tbody class="tbody-hire">
        <tr>
          <td></td>
        </tr>
      </tbody>

    </table>

  </div>

  <hr>

  <h4>Open Searches:</h4>

  <div class="col-12">
    <table class="table order-list" id="role-table">

      <thead>
        <tr>
          <td>Role</td>
          <td>Location</td>
          <td>Active</td>
        </tr>
      </thead>

      <tbody class="tbody-search">
        <tr>
          <td></td>
        </tr>
      </tbody>
    </table>

  </div>
  <h4>Roles Filled:</h4>
  <div class="col-12">
    <table class="table order-list" id="role-table">

      <thead>
        <tr>
          <td class="thead-emp">Name</td>
          <td class="thead-role-fill">Role</td>
          <td class="thead-loc-fill">Location</td>
          <td class="thead-act-fill">Active</td>
        </tr>
      </thead>

      <tbody>
        <tr id="filledRowBody">

        </tr>
      </tbody>
    </table>
  </div>
</div>

<div id="titleBody">

</div> <!-- col-6 -->

1 个答案:

答案 0 :(得分:0)

It turned out that #titleBody was inside of the col-6 div which somehow led to the duplications.