javascript - 可以巧妙地使用动态 html 表作为源数据吗?

标签 javascript jquery r plotly r-markdown

如果我有一个 html 表格,其中包含根据我的文件中的过滤器计算的值,我可以 plotly 读取并根据这些值生成绘图吗?

我不确定回答这个问题是否重要,但我主要使用 R,并使用 r 代码块从我使用 crosstalk 创建的共享数据对象名称 shared_ert 计算总和R 包。

<table id="example" class="cell-border" style="width:100%">
<tr>
<th>Enrolled</th>
<th>Not Enrolled</th>
</tr>
<tr>
<td>
```{r, echo=FALSE, collapse=TRUE, warning=FALSE, message=FALSE}
summarywidget::summarywidget(shared_ert,statistic = 'sum',column = 'Enrolled')
```
</td>
<td>

```{r, echo=FALSE, collapse=TRUE, warning=FALSE, message=FALSE}
summarywidget::summarywidget(shared_ert,statistic = 'sum',column = 'Not Enrolled')

```

</td>
</tr>
</table>

请注意,摘要小部件最终会在每个 td 中生成一个 span 标签。 跨度看起来像 <span id ="waffle" class="summarywidget html-widget html-widge-static-bound">1293</span>

所以表格最终看起来像:

<table id="example" class="cell-border" style="width:100%">
<tr>
<th>Enrolled</th>
<th>Not Enrolled</th>
</tr>
<tr>
<td>
<span id ="waffle" class="summarywidget html-widget html-widge-static-bound">1293</span>
<script type="application/json" data-for="waffle">
### a bunch of data appears here, from which the 1293 value is derived
</script>

</td>
<td>
<span id ="iron" class="summarywidget html-widget html-widge-static-bound">948</span>
<script type="application/json" data-for="iron">
### a bunch of data appears here, from which the 948 value is derived
</script>


</td>
</tr>
</table>

根据我对 javascript 世界的有限理解,我需要我的数据看起来像这样

var data = [
{
x: ['giraffes', 'orangutans', 'monkeys'],
y: [20, 14, 23],
type: 'bar'
  }
];

这样我就可以用类似的东西制作一个 plotly :

Plotly.newPlot('myDiv', data);

(直接来自 https://plotly.com/javascript/bar-charts/)

如果我正确理解问题,我需要阅读 html 表 example并创建一个 var拿着 table 的。在对 SO 和整个网络进行大量搜索之后,我的猜测是这里的解决方案:HTML Table to JSON将表格拉入正确的格式。我在努力

```{js}
function tableToJson(table) {
var data = [];

// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
    headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}

// go through cells
for (var i=1; i<table.rows.length; i++) {

    var tableRow = table.rows[i];
    var rowData = {};

    for (var j=0; j<tableRow.cells.length; j++) {

        rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

    }

    data.push(rowData);
}       

return data;
}

var tabdata = $document.getElementById('#example').tableToJSON();            

```

我认为从这里开始,我需要从当前状态的表中读取数据,因此我使用按钮和 onclick 生成绘图,如下所示:

<button type="button" onclick="Plotly.newPlot('myDiv',tabdata);">Make Plot</button>

点击后,绘图出现,但没有任何数据点。

我的方法论可能偏离了轨道,所以我推迟回答最初的问题:我可以根据动态 html 表进行绘图阅读和生成绘图吗?

我们将不胜感激为建立实现此目的的方法提供的任何帮助。

最佳答案

您需要使用键 xy 生成您的 json。所以,这里的 x 值将是您的 header ,即:th 标签和 y 值将是 tdvalues 。现在,如果您的表中只有一行,您可以简单地创建 JSON 对象,然后使用键将值压入其中,即:data["x"]、data["y"] ..等等

演示代码:

function tableToJSON(table) {
  var data = {}; //create obj
  data["x"] = [] //for x & y
  data["y"] = []
  data["type"] = "bar"
  for (var i = 0; i < table.rows[0].cells.length; i++) {
    data["x"].push(table.rows[0].cells[i].innerHTML.toLowerCase().trim()); //push x values
  }
  for (var i = 1; i < table.rows.length; i++) {
    var tableRow = table.rows[i];
    for (var j = 0; j < tableRow.cells.length; j++) {
      data["y"].push(parseInt(tableRow.cells[j].querySelector(".summarywidget").textContent.trim()));
      //push y values
      console.log(tableRow.cells[j].querySelector(".summarywidget").textContent.trim())
    }
  }

  return data;
}

function draw() {
  var tabdata = tableToJSON(document.getElementById('example'));
  tester = document.getElementById('tester');
  Plotly.newPlot(tester, [tabdata])
}
<script src="https://cdn.plot.ly/plotly-2.1.0.min.js"></script>
<table id="example" class="cell-border" style="width:100%">
  <tr>
    <th>Enrolled</th>
    <th>Not Enrolled</th>
  </tr>
  <tr>
    <td>
      <span id="waffle" class="summarywidget html-widget html-widge-static-bound">1293</span>
      <script type="application/json" data-for="waffle">
        ###
        a bunch of data appears here, from which the 1293 value is derived
      </script>

    </td>
    <td>
      <span id="iron" class="summarywidget html-widget html-widge-static-bound">948</span>
      <script type="application/json" data-for="iron">
        ###
        a bunch of data appears here, from which the 948 value is derived
      </script>


    </td>
  </tr>
</table>

<button type="button" onclick="draw()">Make Plot</button>
<div id="tester" style="width:600px;height:250px;"></div>


现在,如果您的表中有多行,您需要生成这些值的 JSON 数组。为此,您需要保留 main_array,然后将值压入其中每次迭代的 main_array。

演示代码:

function tableToJSON(table) {
  var main_array = [] //for main array
  var for_x = [] //for x values
  for (var i = 0; i < table.rows[0].cells.length; i++) {
    for_x.push(table.rows[0].cells[i].innerHTML.toLowerCase().trim()); //push value 
  }
  for (var i = 1; i < table.rows.length; i++) {
    var tableRow = table.rows[i];
    var data = {}; //create obj..
    data["y"] = [] //for y values
    for (var j = 0; j < tableRow.cells.length; j++) {
      data["y"].push(parseInt(tableRow.cells[j].innerHTML.trim())); //push y values
    }
    //save other values..
    data["x"] = for_x
    data["type"] = "bar"
    data["name"] = "Rows" + i
    main_array.push(data) //push values in main array
  }
  //console..[{},{}..]
  return main_array;

}

function draw() {
  var tabdata = tableToJSON(document.getElementById('example'));
  tester = document.getElementById('tester');
  //pass it here
  Plotly.newPlot(tester, tabdata, {
    barmode: 'stack'
  })
}
<script src="https://cdn.plot.ly/plotly-2.1.0.min.js"></script>
<table id="example" class="cell-border" style="width:100%">
  <tr>
    <th>Enrolled</th>
    <th>Not Enrolled</th>
  </tr>
  <tr>
    <td>
      123
    </td>
    <td>
      125
    </td>
  </tr>
  <tr>
    <td>
      121
    </td>
    <td>
      127
    </td>
  </tr>
</table>

<button type="button" onclick="draw()">Make Plot</button>
<div id="tester" style="width:600px;height:250px;"></div>

关于javascript - 可以巧妙地使用动态 html 表作为源数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68103456/

相关文章:

javascript - 如何在页面加载事件上获取服务器上的客户端计算机时间

javascript - 尝试使用 jquery 工具将鼠标悬停在覆盖层上

javascript - 停用最后一列的点击事件

javascript - 当用户点击动态创建的链接时如何调用 JS 方法。 JQuery、ASP.NET MVC

r - 从中央银行网页下载经济官方数据

R tm 包和西里尔文字

javascript - 我该怎么做才能从数据库的表中打印该特定选项的所有数据?

javascript - 如何制作标题和第一列固定在垂直和水平滚动条上的表格?

javascript - Chrome 扩展回调传递两个值,其中一个显示未定义?

c++ - 我如何将 std::function 作为函数指针传递?