javascript - 将对象元素传输到表
问题描述
我遍历一个对象以将其元素传输到 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>
解决方案
tableCalNum.value = ingrList[i][k].cal;
使用 .value 设置 tableCalNum
推荐阅读
- javascript - 我如何设计这些卡片,以便在点击时打开指向新页面的链接?
- javascript - 在 Flutter 中使用 Html 和 Javascript
- splash-screen - 如何在 yocto 中加载用户空间之前显示引导屏幕
- apache-spark - 是否可以使用 mapgroupwithstate 作为滑动窗口
- prisma2 - 棱镜迁移缺少上下功能
- python - 在 Robot Framework 中为连接的所有查询设置架构
- javascript - index.js:1 警告:失败的道具类型:不推荐使用“ForwardRef(ButtonBase)”的道具“buttonRef”。改用`ref`
- firebase - Flutter GetX 变量发生变化,但 UI 没有
- java - javax.persistence.PersistenceException:没有名为 PERSISTENCE 的 EntityManager 的持久性提供程序
- python - tf.keras.models.load_model 返回 ValueError:应在输入列表上调用合并层