在HTML表中显示JSON,并添加行

Display JSON in an HTML table and also add rows

本文关键字:添加行 JSON 显示 HTML      更新时间:2023-09-26

我正在寻找一些psuedo代码来帮助我制定策略。以下是我要做的:

我收到一个JSON对象,其中包含显示在HTML表中的数据。有时我使用$each,有时我使用for循环。有很多方法可以做到这一点。假设它是一个包含IP、MAC和Name列的表。JSON看起来是这样的:

[{"mode": "ftp"},{"IP": "123.123"},{"MAC": "445566"}]

但是,当我需要为用户创建一个新行以输入IP、MAC和Name的新数据时,我会重复自己的操作,并创建一个创建新行的函数-它为每个值创建一个新的<tr><td>,等等。由于我的表由静态文本字段和每个字段旁边的隐藏输入组成(单击"编辑"按钮时切换可见性),在我的应用程序中,这相当多的代码需要两次。

有没有一种优雅的方法可以用更少的代码来实现这一点?我在想,我不直接在表中显示数据,而是创建一个名为addRow的函数,它的参数是每行的数据,然后页面可以最初为每行调用该函数,当我创建新行时再调用。

一些psuedo代码会很好,我可以填补空白,我只想知道是否有其他方法可以实现这一点,或者是否有一种流行的Javascript模式可以实现这类功能。

编辑:我使用第三方插件的请求未被批准。我知道DataTables很棒,但对于这个,我只能靠自己了!

我会选择https://datatables.net(MIT许可证)

它非常"优雅"且快速,允许您使用json数据初始化表。它还具有易于使用的addrow/inline编辑功能。

  • Json Init:

https://www.datatables.net/examples/data_sources/ajax.html

  • AddRow:

https://datatables.net/examples/api/add_row.html

  • 内联编辑:

https://editor.datatables.net/examples/inline-editing/simple

我认为您的最初想法是创建一个addRow函数并调用它,这是正确的。但是,请记住,您希望编辑尽可能小的DOM,因为每个appendinsert通常都会导致重绘。。。因此,也许我们最好使用addRows函数来代替addRow,它将允许您一次附加多行。你可以用你的数据行调用它来做一个单独的附加。然后,当您只添加一行时,只需编辑数据,使其成为长度为1的数组。也就是说,传递它[rowData](添加括号使外层成为长度为1的数组),而不仅仅是rowData

也就是说,

  // Create the table element and add the headers.
  function createTableAddHeaders(){
    // however you want to do it.
  }
  // Each element of 'rowsToAppend' will be transformed into
  // a table row. Append rows is agnostic as to whether
  // the input rows already exist in the table. 
  // It will just keep appending the input to the table
  function appendRows(rowsToAppend){
    // code to append input 'rowsToAppend'to the tableElem 
  }
  // Example Call ----------------------------
  // This is the data we will use to create the original table
  var originalRows = [
    ["Row Number", "id1", "id2", "id3"], // Header
    ["Row 1", 1,2,3], // data
    ["Row 2", 4,5,6]  // data
  ];
  createTableAddHeaders();  // Create table
  appendRows(originalRows); // Append original data to the table

  // Now we have new data we want to append.
  var newRow = ["Row 3: New Row", 7, 8, 9];
  // Wrap it in a [] when calling appendRows so the
  // outer layer becomes an array of length one
  appendRows([newRow]);