搜尋

首頁  >  問答  >  主體

如何在 Tabulator JS 中將自訂格式化程式與預先定義格式化程式結合?

我使用 Tabulator JS,並且有 2 列包含數字資料。首先,我使用了帶有formatterParams 參數的內建money 格式化程序,對於第二個,我想應用完全相同的、具有相同參數的,但還要添加,例如,單元格的顏色。如何以自訂格式套用formatterParams

new Tabulator("#data-table", {
      data: data,
      layout: "fitColumns",
      columns: [{
          title: "Length",
          field: "length",
          formatter: zeroValueFormatter,
          formatterParams: {
            thousand: " ",
            precision: false
          }
        },
        {
          title: "New length",
          field: "newLength",
          formatter: "money",
          formatterParams: {
            thousand: " ",
            precision: false
          }
        ],
      });


function zeroValueFormatter(cell, formatterParams /* ? */) {
    if (cell.getValue() === 0) {
        cell.getElement().style.backgroundColor = "#add8e6";
    }    
    return cell.getValue();
}

P粉676588738P粉676588738469 天前741

全部回覆(1)我來回復

  • P粉592085423

    P粉5920854232023-09-14 12:37:49

    一種選擇是使用 rowFormatter 並將格式套用到您需要的特定欄位。在您的範例中,是 length 列。這樣,您可以在兩列的列設定層級使用內建的 money 格式化程序,但在行層級套用其他格式。這是一個例子:

    const data = [
      { length: 0, newLength: 10000 },
      { length: 2000, newLength: 20000 },
      { length: 3000, newLength: 0 }
    ]
    
    const table = new Tabulator("#data-table", {
      data: data,
      layout: "fitColumns",
      rowFormatter: zeroValueFormatter,
      columns: [{
          title: "Length",
          field: "length",
          formatter: "money",
          formatterParams: {
            thousand: " ",
            precision: false
          }
        },
        {
          title: "New length",
          field: "newLength",
          formatter: "money",
          formatterParams: {
            thousand: " ",
            precision: false
          }
        }
      ],
    });
    
    function zeroValueFormatter(row) {
      const rowData = row.getData()
    
      if (rowData['length'] === 0) {
        row.getCell('length').getElement().style.backgroundColor = "#add8e6";
      }
    
    }
    <link href="https://unpkg.com/tabulator-tables@5.5.1/dist/css/tabulator.min.css" rel="stylesheet" />
    <script type="text/javascript" src="https://unpkg.com/tabulator-tables@5.5.1/dist/js/tabulator.min.js"></script>
    <div id="data-table"></div>

    回覆
    0
  • 取消回覆