如何在脚本中向此 div-table 添加 table header?

How to add a table header to this div-table within a script?

我得到了这个 div-table 动态填充,但我找不到向它添加 header 的方法,考虑到它的构建方式。

HTML片:

<div class="block div-table" id="sidebar-record-block"></div>

这是动态填充 table 的脚本:

function showRecord(record) {
    if (record.length) {
      for (var i = 0; i < record.length; i++) {
        // build field name on the fly, formatted field-1234
        var str = '' + i;
        var fieldId = 'field-' + ('0000' + str).substring(str.length)

        // If this field # doesn't already exist on the page, create it
        if (!$('#'+fieldId).length) {
          var newField = $($.parseHTML('<div id="'+fieldId+'"></div>'));
          $('#sidebar-record-block').append(newField);
        }

        // Replace content of the field div with new record
        $('#'+fieldId).replaceWith('<div id="'+fieldId+'" class="div-table-row"></div>');
        $('#'+fieldId).append('<input id=checkBox type="checkbox"</input>')
                      .append($('<div class="div-table-th">' + record[i].heading + '</div>'))
                      .append('<div class="div-table-td">' + record[i].cellval + '</div>')             
      }  
    }

css 是这样的:

.div-table {
    display: table;
    width: auto;
    border-spacing: 3px;
  }

  .div-table-row {
    display: table-row;
    width: auto;
    clear: both; 
 }

  .div-table-td,
  .div-table-th {
    display: table-cell;
    width: 190px;
    background-color: rgb(245, 241, 239);
  }

这是预期的结果: 感谢您的帮助!

实际上,您几乎已经拥有了所需的一切。诀窍是将行的标题作为不同样式的行元素添加到自定义 table.

例如:

.div-table {
    display: table;
    width: auto;
    border-spacing: 3px;
  }

  .div-table-row {
    display: table-row;
    width: auto;
    clear: both; 
 }

  .div-table-td,
  .div-table-th {
    display: table-cell;
    width: 190px;
    background-color: rgb(245, 241, 239);
  }
  
  .div-table-header {
    display: table-cell;
    width: 190px;
    text-align: center;
  }
<div class="block div-table" id="sidebar-record-block">
  <div class="div-table-row">
    <div>Sel</div>
    <div class="div-table-header">Color</div>
    <div class="div-table-header">Hex</div>
  </div>
  <div class="div-table-row">
    <input type="checkbox">
    <div class="div-table-th">amarelo suave</div>
    <div class="div-table-td">EEEA97</div>
  </div>
  <div class="div-table-row">
    <input type="checkbox">
    <div class="div-table-th">verde</div>
    <div class="div-table-td">00FF00</div>
  </div>
</div>

在运行时动态创建它与您已有的代码没有太大区别。

只需在 for-loop 的开头添加以下内容:

if(i==0) {
   $('#sidebar-record-block').append($($.parseHTML('<div class="div-table-row"><div>Sel</div><div class="div-table-header">Color</div><div class="div-table-header">Hex</div></div>')));
      }