javascript - 将这些表格输出转换为 div 输出

标签 javascript jquery html css csv

最近我在这里寻求有关 javascript 的帮助。我需要能够解析 CSV 文件并将其输出为 HTML 的工具。

有人能够极大地帮助我。唯一的问题是它输出为单行表。在 CSV 文件中,每一行没有特定数量的列/数据,这意味着行数据的长度不同。

我一直在尝试做的是编写一些 if 语句,仅选择“姓氏”或“知名度”之类的内容,这样我就可以对结果进行排序。

最好的方法是什么?我需要设置输出数据的样式,所以我认为 div id 会比表格更好。另外,我应该在代码中的什么地方进行编辑(我的 javascript 知识非常初级)。

我试过的 if 语句(可能完全错误):

  function firstName($container){
      var firstN = $container;
      var n = firstN.includes("First Name");

    if (n != 0){
        document.getElementById("first_name").innerHTML="First name = ";
        return;
    }
    }

主要代码块(CSV 文件可以在 http://www.fooda.website/testResults.csv 找到):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery-1.12.3.min.js" type="text/javascript">
</script>
<title>Untitled Document</title>
<script type="text/javascript">
// ============================
// Allow for a cached result
// ============================
var csvRows = [];
// ============================

// ============================
// Given an array of rows build a table.
// ============================
function buildTable(csvRows){
  // Our base result
  var $table = $("<table cellpadding=\"2\" cellspacing=\"0\"></table>");

  // ============================
  // For each row in the CSV build a <tr /> and append it to the <table />
  // ============================
  $table = csvRows.reduce(function($table, csvRow){

    // For this demo just take the first few cells/columns
    var csvRowCells = csvRow.split(",");

    // Our base table row
    var $tr = $("<tr>/tr>");

    // ============================
    // For each cell row build a <td /> and append it to the <tr />
    // ============================
    $tr = csvRowCells.reduce(function($tr, csvRowCell){
      return $tr.append($("<td>/</td>").text(csvRowCell));
    }, $tr);
    // ============================

    // Add our new <tr /> to the table then return the table
    return $table.append($tr);
  }, $table);
  // ============================

  return $table;
}
// ============================

// ============================
// Given an array of rows, randomly select one (as an array) and build a table with it.
// ============================
function fillContainerWithTable(csvRows, $container){
  var randomRow = [csvRows[Math.floor(Math.random() * csvRows.length)]];
  var $table = buildTable(randomRow);
  $container.append($table);
}
// ============================

// ============================
// the click handler
// ============================
function myFunction(){
  // some random csv I found...
  var uri = "http://www.fooda.website/testResults.csv";
  var $container = $("#wrap");

  // You probably want a clean slate.
  $container.empty();

  // ============================
  // If we have the data locally already just use it.
  // ============================
  if (csvRows.length !== 0){
    console.log("using local data...");
    fillContainerWithTable(csvRows, $container);
    return;
  }
  // ============================

  console.log("fetching remote data...");

  $.get(uri, function(data){
    csvRows = data.split("\n");
    fillContainerWithTable(csvRows, $container);
  });
}
// ============================
</script>
<style type="text/css">
body {
  font-family: arial, helvetica, sans-serif;
  font-weight: normal;
  font-size: 13px;
  color: #000;
  text-align: left;
  margin: 3px 0px;
}

#wrap {
  padding: 20px;
}

#wrap table {
  border: solid 1px;
  border-collapse: collapse;
  background-color: aliceblue;
  height:400px;
  width:100%;
}

#first_name {
    height:200px;
    width:200px;
    background-color:#0C0;
}

</style>
</head>



<body>


<button onclick="myFunction()">Click me</button>
<div id="wrap"></div>

<div id="first_name">
</div><!--first_name-->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


</body>
</html>

提前致谢!

最佳答案

简短的回答是“这是关于 SO 的许多‘我如何将 JSON 转换为 HTML 表格’问题的重复”,最后我只是向你指出其中的一些问题,但我想带您完成它。

CVS(逗号分隔值)看起来像

Col1,Col2,Col3,Col4
row1value1,row1value2,row1value3
row2value1,row2value2
row3value1,,row3value3,row3value4

虽然不是必然这种情况,但您可以将 CSV 视为一种非常紧凑的纯文本写入表格的方式,其中每一行的值都按相同的顺序(如表格列)并且为空单元格看起来像“,,”。如果上面的 csv 是一个表格(例如,如果您将其导入 Excel 等),它将是

Col1       Col2       Col3       Col4
row1value1 row1value2 row1value3
row2value1 row2value2
row3value1            row3value3 row3value4

另一方面,您的数据实际上是一个 JSON“对象”列表,每行一个。在 JSON 中,对象 包含在 { } 中并且由“键/值”对组成。一个 JSON 对象看起来像

{"key1":"value1", "key2":"value2"}

JSON 让您可以将对象分组到数组 中。 [ ] 中包含一个 JSON 数组.

在 JSON 中,上表看起来像

[{'Col1':'row1value1','Col2':'row1value2','Col3':'row1value3'},
 {'Col1':'row1value1','Col2':'row1value2'},
 {'Col1':'row1value1','Col3':'row1value3','Col4':'row1value4'}]

使用 JSON 时,您可以说“遍历数组中的每个对象”和“对于当前对象,给我 Col2 值”。 (请注意,这意味着相关的 JSON 对象不必以相同的顺序列出键/值对,并且您不必指定缺失值。)如果您知道数组中的每个可能的键(在这种情况下,会是 Col1、Col2、Col3 和 Col4)你可以说

"Loop through the array, put each object in a <tr>, and for each object first put the Col1 value in a <td>, then put the Col2 value in a <td>, then put the Col3 value in a <td>, then put the Col4 value in a <td>."

这正是您想要做的……事实证明,已经有很多工具可以做到这一点!唯一挡在你和使用它们之间的是放一个 [在文件的开头,一个 ,在除最后一行之外的每一行的末尾,以及一个 ]在文件的末尾。如果你能做到这一点,那你就走运了。如果这是静态数据,只需在文本编辑器中打开数据并使用查找/替换来添加行尾逗号。如果它是动态生成的,您将不得不想出一种添加内容的方法(解决方案类似于 [ ,将文件拆分为 } ,对拆分数据的每个 block 进行添加后跟一个 , 除非它是最后一个 block ,然后添加一个 ] ,然后通过 JSON-to-HTML-table 工具运行它)。具体如何操作由您决定——如果您遇到困难,一定要提出一个新问题“我如何才能将 json 对象列表转换为 json 数组”。我不是 JSON 专家,我敢打赌有一些标准的方法可以做到这一点

这里有几个很有前途的 JSON 到 HTML 表解决方案。我很想知道其中之一是否适合您!

关于javascript - 将这些表格输出转换为 div 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39297958/

相关文章:

javascript - 将文本注入(inject)img标签的 "URL"部分

javascript - 如何在 ElasticSearch 和 ElasticSearch Javascript 客户端中按 ID 和 ID 查找

javascript - 自定义验证无法使用 Angular Js 工作

javascript - 如何 .animate() 背景图像大小

Javascript:如何在服务器端(后端)执行?

javascript - 单击菜单更改 Sprite 和颜色

javascript - 通过使用 Javascript 单击图片来更改图片

javascript - 从 URL 获取查询字符串并将其传递给 Href

javascript - 防止错误提示 xss 上的 img 标记以获取 GET

html - 如何使用仅适用于移动设备的 Bootstrap 隐藏部分文本