制表符/以编程方式校正表数据(从HTML <table>加载)

时间:2019-08-07 13:50:42

标签: javascript tabulator

Tabulator是由未知 HTML <table>(具有TH标头,因此所有列都有名称)创建的。

因此,除mutator外,无法触发任何callbackhtmlImported:function()...。

由于HTML <table>包含格式错误的DATE值,因此我需要访问所有fields中的所有rows才能发现并更正这些值。

整个代码是:

<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://unpkg.com/tabulator-tables@4.3.0/dist/css/">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.3.0/dist/js/tabulator.min.js"></script>
</head><body>
<table id="tablexxx">
 <tr>
  <th>Name</th><th>Favorite Color</th><th>date</th></tr>
 <tr><td>Bob</td><td>Yellow</td><td>1/1/2001</td>
 </tr>
 <tr><td>Michelle</td><td>Purple</td><td>2/1/2000</td>
 </tr>
</table>
<div id="tablexxx"></div>

<script>
var tablexxx = new Tabulator("#tablexxx", {});

var rows = tablexxx.getRows();
rows.forEach(function(row)
{ var rowData = row.getData();
  rowData.forEach(function(cell) // <<< HOW TO DO IT RIGHT???
  {
    // get row field NAME
    var field = cell.name;       // <<< HOW TO DO IT RIGHT???
    if(field.indexOf("date") >= 0)
    {
       // get colum field VALUE
       var date = cell.value;   // <<< HOW TO DO IT RIGHT???

       // make new value using proper format
       var ndate = date[0] + date[1] + date[2]; // TODO

       // update row with {"date":"01/02/2000"}
       row.update("{" + field + ":" + ndate + "}"); 
    }
  });
});
</script></body></html>

有人可以告诉我如何"DO IT RIGHT"滞后上方的指定<script>部分吗?

1 个答案:

答案 0 :(得分:1)

希望我能理解您想要完成的任务...

如果日期和月份为<10,则将日期和月份填充为0。

首先获取带有数据字段的列,然后遍历该列中的每个单元格,分割日期并更新该单元格。 我实际上不知道为什么表中没有空行(这就是if (value)的作用)。它是制表符插入的东西。

function pad(num, size) {
    var s = num + "";
    while (s.length < size) s = "0" + s;
    return s;
}

var tablexxx = new Tabulator("#tablexxx", {});
var dateColumn = tablexxx.getColumn("date");
for (var cell of dateColumn.getCells()) {
  var value = cell.getValue();
  if (value) {
    value = value.split("/")
    cell.setValue(pad(value[0], 2) + "/" + pad(value[1], 2) + "/" + value[2]);
  }
}
<link rel="stylesheet" href="https://unpkg.com/tabulator-tables@4.3.0/dist/css/">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.3.0/dist/js/tabulator.min.js"></script>

<table id="tablexxx">
 <tr>
  <th>Name</th><th>Favorite Color</th><th>date</th></tr>
 <tr><td>Bob</td><td>Yellow</td><td>1/1/2001</td>
 </tr>
 <tr><td>Michelle</td><td>Purple</td><td>2/1/2000</td>
 </tr>
</table>