可以将动态 html 表用作源数据吗?

2023-09-30前端开发问题
4

本文介绍了可以将动态 html 表用作源数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

If I have an html table that contains values that are calculated based on filters within my file, can I get plotly to read and produce a plot based on those values?

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

I'm not sure that it matters to answering this question, but I use R primarily, and use the r code chunks calculate sums from a sharedData object names shared_ert that I created with the crosstalk package for 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 标签.跨度看起来像

所以表格最终看起来像:

So the table ends up looking like:

<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 世界的有限理解,我需要我的数据看起来像

From my limited understanding of the world of javascript, I need my data to look something like

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

这样我就可以得到一个类似这样的情节:

So that I can get a plot produced with something like:

Plotly.newPlot('myDiv', data);

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

如果我正确理解了问题,我需要阅读 html 表 example 并创建一个保存该表的 var.经过大量搜索 SO 和一般网络后,我的猜测是这里的解决方案:HTML Table to JSON 将表格拉入正确的格式.我在努力

If I understand the problem correctly, I need to read the html table example and create a var that holds the table. After much searching around SO and the web in general, my guess is that the solution here: HTML Table to JSON pulls the table into the correct format. I'm trying

```{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 生成绘图,如下所示:

I think from here, I need plotly to read the data from the table in it's current state, so I produce the plot using a button and onclick, as follows:

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

点击后,会出现绘图,但在任何地方都没有数据点.

Upon clicking, the plotly plot appears, but doesn't have a data point anywhere.

我的方法论可能偏离了轨道,所以我顺从最初的问题:我可以根据动态 html 表读取并生成绘图吗?

I might be way off track in my methodology, so I defer to the original question: can I get plotly to read and produce a plot based on a dynamic html table?

非常感谢任何帮助建立为此目的的方法.

Any help establishing a means to this end would be very much appreciated.

推荐答案

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

You need generate your json with keys x & y .So , here x value will be your header i.e : th tags and y values will be tdvalues . Now , if you have only one row in your table you can simply create JSON Object and then push value inside this using key i.e : data["x"] , data["y"]..etc .

演示代码:

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.

Now , if you have mutliple rows in your table you need to generate JSON Array of that values .For that you need to keep main_array and then push values inside this main_array on each iterations.

演示代码:

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>

这篇关于可以将动态 html 表用作源数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Fatal error: Call to a member function fetch_assoc() on a no
业务场景:使用update语句去更新数据库字段。 原因:update接收值不正确。原来代码: $query = "UPDATE student SET date = now() WHERE id = $id";$result = $mysqli-query($query2) or die($mysqli-error); // 问题出现了在这句 $data = $result-fetch_ass...
2024-12-13 前端开发问题
136

layui实现laydate日历控件控制之前日期不可选择
具体实现代码如下: laydate.render({ elem: '#start_time', min:0, //,type: 'date' //默认,可不填}); 只要加一个min参数,就可以控制了。0表示之前的日期不可...
2024-11-29 前端开发问题
133

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 实现实时刷新一个外部的div
主页面上显示了一个合计,在删除和增加的时候需要更改这个总套数的值: //html代码div class="layui-inline layui-show-xs-block" style="margin-left: 10px" id="sumDiv"spanSOP合计:/spanspan${totalNum}/spanspan套/span/div 于是在我们删除这个条数据后,...
2024-11-14 前端开发问题
156

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313