javascript - 如何使用javascript用复选框替换html表中的真/假值

标签 javascript html checkbox

我有一个 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/

相关文章:

javascript - 407 需要代理身份验证(Forefront TMG 需要授权才能完成请求。对 Web 代理过滤器的访问被拒绝。)

javascript - 切换类后,Jquery 将不会选择按钮

Javascript Css Tooltip who to Fix position 当页面结束时

javascript - 在选中复选框之前禁用 jQuery OnClick 事件?

javascript - 如何仅在悬停而不设置样式时禁用 classList

javascript - image() 对象的问题

java - 为 Table 组件中的 CodenameOne TableModel 添加 Checkbox

c++ - 带有使用自定义模型的复选框的qlistview

java - 如何在 Java Jersey 中获取 HTML 选中的复选框

javascript - 有什么方法可以创建扩展数组的对象吗?