我有一个 javascript 对象数组,我用它来动态填充 html 表。我遍历每个对象,一切都很好。但是,其中一个键的值为 true/false,我需要用数组中每个对象的复选框替换该值。我该怎么做?
复选框需要勾选为 false,不勾选为 true,还需要禁用复选框,因为我们不希望用户交互。
// Draw table from 'products' array of objects
function drawTable(tbody) {
var tr, td;
tbody = document.getElementById(tbody);
for (var i = 0; i < products.length; i++) // loop through data source
{
tr = tbody.insertRow(tbody.rows.length);
td = tr.insertCell(tr.cells.length);
td.innerHTML = products[i].ProductName;
td = tr.insertCell(tr.cells.length);
td.innerHTML = products[i].UnitsInStock;
td = tr.insertCell(tr.cells.length);
td.innerHTML = products[i].UnitPrice;
td = tr.insertCell(tr.cells.length);
td.innerHTML = products[i].Discontinued;
td = tr.insertCell(tr.cells.length);
td.innerHTML = document.createElement('button');
}
}
drawTable('table-data')
<h2>Products</h2>
<div class="table-wrapper">
<table id="display-table" class="fl-table">
<thead>
<tr>
<th>Product Name</th>
<th>Units In Stock</th>
<th>Unit Price</th>
<th>Discontinued</th>
</tr>
</thead>
<tbody id="table-data">
</tbody>
</table>
</div>
最佳答案
以下是如何根据数组中名为“checkbox”的字段添加一个复选框列,该字段为 true/false。我只是在此处匹配您的代码,因此很容易理解:
td = tr.insertCell(tr.cells.length);
checkbox = document.createElement('input');
checkbox.setAttribute("type", "checkbox");
checkbox.disabled = true;
checkbox.checked = products[i].checkbox;
td.appendChild(checkbox);
关于javascript - 如何使用javascript用复选框替换html表中的真/假值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57549059/