首页 > 解决方案 > 将对象元素传输到表

问题描述

我遍历一个对象以将其元素传输到 HTML 表。该表有 4 列。其中 2 列是一个数字文本框。来自对象的字符串应该被转移到那些数字文本框中。其中一个已成功转移,金额栏上的一个,但卡路里栏上的一个没有显示。我正在寻找将对象中的指定卡路里数字传输到 HTML 表上的数字文本框的方法。

let mealObj = {
  menu1: {
    menuName: "Steak",
    ingr1: {
      name: "Butter",
      ingrType: "other",
      amount: "2",
      amountType: "tbsp",
      cal: "10",
    },
    ingr2: {
      name: "Parsley",
      ingrType: "vegetable",
      amount: "1",
      amountType: "tsp",
      cal: "1",
    },
    ingr3: {
      name: "Garlic",
      ingrType: "vegetable",
      amount: "1/2",
      amountType: "tsp",
      cal: "20",
    },
    ingr4: {
      name: "Soy Sauce",
      ingrType: "other",
      amount: "1/4",
      amountType: "tsp",
      cal: "20",
    },
    ingr5: {
      name: "Beef",
      ingrType: "meat",
      amount: "3/4",
      amountType: "lbs",
      cal: "200",
    },
    ingr6: {
      name: "Salt",
      ingrType: "other",
      amount: "1/8",
      amountType: "tsp",
      cal: "0",
    },
    ingr7: {
      name: "Pepper",
      ingrType: "other",
      amount: "1/8",
      amountType: "tsp",
      cal: "2",
    },
  },
}

let ingrTable = document.getElementById("ingr-table");

objToTable(mealObj);

function objToTable(ingrList) {
let totalRowLength = ingrTable.rows.length;
  for (let i in ingrList) {
    for (let k in ingrList[i]) {
      if (ingrList[i][k].name !== undefined) {
          let tableAmount = document.createElement("INPUT");
          tableAmount.setAttribute("type", "number");
          tableAmount.id = "table-amount";
          let tableCalNum = document.createElement("INPUT");
          tableCalNum.setAttribute("type", "number");
          tableCalNum.id = "table-cal";

          let row = ingrTable.insertRow(totalRowLength);
          var cell1 = row.insertCell(0);
          var cell2 = row.insertCell(1);
          var cell3 = row.insertCell(2);
          var cell4 = row.insertCell(3);
          var cell5 = row.insertCell(4);
          cell1.innerHTML = ingrList[i][k].name;
          cell2.appendChild(tableAmount);
          tableAmount.value = eval(ingrList[i][k].amount);
          cell3.innerHTML = ingrList[i][k].amountType;
          cell4.appendChild(tableCalNum);
          tableCalNum = ingrList[i][k].cal;
      }
    }
  }
}
<table id="ingr-table">
          <tr>
            <th>Ingredient</th>
            <th colspan="2">Amount</th>
            <th>Calorie</th>
            <th></th>
          </tr>
        </table>

标签: javascripthtml

解决方案


tableCalNum.value = ingrList[i][k].cal;

使用 .value 设置 tableCalNum


推荐阅读