簡體   English   中英

如何將對象數組中的數據顯示到表中

[英]how to show data to table from an array of objects

我正在嘗試根據用戶輸入制作數據表。 我發現了這個解決方案,我正在根據用戶輸入制作對象並將它們推送到數組中。 在那之后,我正在做一個for循環來制作td。 但不知何故,這些數據不是逐行出現,而是並排出現。 我在這里做錯了什么,每次我刷新頁面時數組都變空了如何防止這種情況幫助我解決 tnx。

 const form = document.getElementById("form");
    const carDatas = [];

class Car {
  constructor(plate, carMaker, carModel, carOwner, carPrice, carColor) {
    (this.plate = plate),
      (this.carMaker = carMaker),
      (this.carModel = carModel),
      (this.carOwner = carOwner),
      (this.carPrice = carPrice),
      (this.carColor = carColor);
  }
}

form.addEventListener("submit", (e) => {
  const plate = document.getElementById("plate").value;
  const carMaker = document.getElementById("carMaker").value;
  const carModel = document.getElementById("carModel").value;
  const carOwner = document.getElementById("carOwner").value;
  const carPrice = document.getElementById("carPrice").value;
  const carColor = document.getElementById("carColor").value;

  const carDetails = new Car(
    plate,
    carMaker,
    carModel,
    carOwner,
    carPrice,
    carColor
  );
  carDatas.push(carDetails);
  console.log(carDetails);

  for (let i = 0; i < carDatas.length; i++) {
    document.getElementById(
      "data"
    ).innerHTML = ` <td>${carDatas[i].plate}  </td>
     <td>${carDatas[i].carMaker}  </td>
     <td>${carDatas[i].carModel}  </td>
     <td>${carDatas[i].carOwner}  </td>
     <td>${carDatas[i].carPrice}  </td>
     <td>${carDatas[i].carColor}  </td>`;
  }

  e.preventDefault();
});

這是我的表格 HTML

<div class="database">
    <h1>Cars Database</h1>
    <table>
      <tr>
        <th>LICENCE</th>
        <th>MAKER</th>
        <th>MODEL</th>
        <th>OWNER</th>
        <th>PRICE</th>
        <th>COLOR</th>
      </tr>
      <tr id="data"></tr>
    </table>
  </div>
<pre>This is what I recommend I changed your code to add <tr></tr> to each line that's to be created and wrap your <tr> inbetween and tbody tag and use the first line has a head.</pre>

<pre>For the code:</pre>
<code>
for (let i = 0; i < carDatas.length; i++) {
document.getElementById(
  "data"
).innerHTML = `<tr><td>${carDatas[i].plate}  </td>
 <td>${carDatas[i].carMaker}  </td>
 <td>${carDatas[i].carModel}  </td>
 <td>${carDatas[i].carOwner}  </td>
 <td>${carDatas[i].carPrice}  </td>
 <td>${carDatas[i].carColor}  </td> </tr>`;
}

e.preventDefault();



<body>
<div class="database">
<h1>Cars Database</h1>
    <table>
        <thead>
          <tr>
            <th>LICENCE</th>
            <th>MAKER</th>
            <th>MODEL</th>
            <th>OWNER</th>
            <th>PRICE</th>
            <th>COLOR</th>
          </tr>
        </thead>
        <tbody id="data">   <tbody>
    </table>
</div>

</body>
</code>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM