创建表时D3问题

时间:2018-05-03 22:46:43

标签: d3.js html-table

我正在尝试根据我创建的数据创建一个表。 数据如下:

var data;
data = [{'watershed' : 'A', 'values' : [{'ID' : 1001, 'Time' : 10, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1002, 'Time' : 11, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1003, 'Time' : 12, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1004, 'Time' : 13, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1005, 'Time' : 14, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1006, 'Time' : 15, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1007, 'Time' : 16, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1008, 'Time' : 17, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1009, 'Time' : 18, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15}]}]
var masterTable = d3.select('#masterDataTable');
var masterTableTR = masterTable.append('tr');
var watershedTable = masterTableTR.selectAll("table")
                                  .data(data)
                                  .enter()
                                  .append('td')
                                  .style('vertical-align','top')
                                  .append('table')
                                  .attr('class', 'watershedTable')
                                  .style('border-collapse', 'collapse');
var headings = watershedTable.append('thead')
                             .append('tr')
                             .append('th')
                             .text(function(d) {
                                return d.watershed;})
                             .attr('colspan', 5);
var tableBodies = watershedTable.append('tbody')
                                .selectAll('tr')
                                .data(function(d) {
                                    return d.values;
                                    })
                                .enter()
                                .append('tr')
                                .selectAll('td')
                                .data(function(d) {
                                        console.log(d)
                                        return d; })
                                .enter()
                                .append('td')
                                .style('border', 'solid black 1px')
                                .html(function(d) {
                                    return d;});

当我运行此代码时,我只获得了一个在html页面顶部的分水岭。我的表应该如下:

enter image description here

我正在学习基于try和error方法的d3。 有人可以帮我解决我的问题吗?

2 个答案:

答案 0 :(得分:1)

d3可以使用.html输入html,如果数据已经提供给对象,则可以在不再使用.data()的情况下使用它

var data;
data = [{'watershed' : 'A', 'values' : [{'ID' : 1001, 'Time' : 10, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1002, 'Time' : 11, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1003, 'Time' : 12, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1004, 'Time' : 13, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1005, 'Time' : 14, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1006, 'Time' : 15, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1007, 'Time' : 16, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1008, 'Time' : 17, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15},
        {'ID' : 1009, 'Time' : 18, 'Precipitation' : 12, 'Flow' : 13, 'Stage' : 15}]}]
var masterTable = d3.select('#masterDataTable');
var masterTableTR = masterTable.append('table')                              
                                  .style('vertical-align','top')
                                  .attr('class', 'watershedTable')
                                  .style('border-collapse', 'collapse');
                                  
var watershedTable = masterTableTR.selectAll("td")
                                  .data(data)
                                  .enter()

                                  
var headings = watershedTable.append('thead')
                             .html(function(d) {
                             var html ='<tr> <th colspan="5">'+d.watershed +'</th></tr>'
                             +'<tr>'
                              +'<th> ID </th>'
                              +'<th> Time </th>'
                              +'<th> Precipitation </th>'
                              +'<th> Flow </th>'
                              +'<th> Stage </th>'
                             + '</tr>'
                                return html
                               })
                             
                             
var tableBodies = watershedTable.append('tbody')
                                .selectAll('tr')
                                .data(function(d) {
                                    return d.values;
                                    })
                                .enter()
                                .append('tr')
                                
                                
      tableBodies.style('border', 'solid black 1px')
                                .html(function(d,i) {
                              
                                var html =  '<td>' +d.ID +'</td>'
                                            + '<td>' +d.Time +'</td>'
                                           + '<td>' +d.Precipitation +'</td>'
                                            + '<td>' +d.Flow +'</td>'
                                            + '<td>' +d.Stage +'</td>'
                        
      
                                    return html
                                  });
thead {color:green;}
tbody {color:blue;}
tfoot {color:red;}

table, th, td {
    border: 1px solid black;
    padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id = "masterDataTable"> </div>

答案 1 :(得分:1)

可排序表可能对此数据有用,

<!DOCTYPE html>
<meta charset="utf-8">
<style>
  table {
    width: 60%;
    border-collapse: collapse;
    margin: 0px auto;
  }

  /* Zebra striping */

  tr:nth-of-type(odd) {
    background: #eee;
  }

  th {
    background: #333;
    color: white;
    font-weight: bold;
    cursor: s-resize;
    background-repeat: no-repeat;
    background-position: 3% center;
  }

  td,
  th {
    padding: 6px;
    border: 1px solid #ccc;
    text-align: left;
  }

  th.des:after {
    content: "\21E3";
  }

  th.aes:after {
    content: "\21E1";
  }
</style>

<body>
  <div id="page-wrap">
  </div>
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <script>
    

    var data = [
      // 'watershed': 'A',
      // 'values': [{
      {
        'ID': 1001,
        'Time': 10,
        'Precipitation': 12,
        'Flow': 13,
        'Stage': 15
      },
      {
        'ID': 1002,
        'Time': 11,
        'Precipitation': 12,
        'Flow': 13,
        'Stage': 15
      },
      {
        'ID': 1003,
        'Time': 12,
        'Precipitation': 12,
        'Flow': 13,
        'Stage': 15
      },
      {
        'ID': 1004,
        'Time': 13,
        'Precipitation': 12,
        'Flow': 13,
        'Stage': 15
      },
      {
        'ID': 1005,
        'Time': 14,
        'Precipitation': 12,
        'Flow': 13,
        'Stage': 15
      },
      {
        'ID': 1006,
        'Time': 15,
        'Precipitation': 12,
        'Flow': 13,
        'Stage': 15
      },
      {
        'ID': 1007,
        'Time': 16,
        'Precipitation': 12,
        'Flow': 13,
        'Stage': 15
      },
      {
        'ID': 1008,
        'Time': 17,
        'Precipitation': 12,
        'Flow': 13,
        'Stage': 15
      },
      {
        'ID': 1009,
        'Time': 18,
        'Precipitation': 12,
        'Flow': 13,
        'Stage': 15
      }
    ]

    // parse the time, minute:second
    // var parseTime = d3.timeParse("%M:%S");
    var timeformat = d3.timeFormat("%M:%S");

    // format the data etc.
    data.forEach(function(d) {
      // d.clocktime = parseTime(d.clocktime);
      // d.racetime = parseTime(d.racetime);
      // d.points = +d.points;
      d.ID = +d.ID;
      // 'Time': 18,
      d.Time = +d.Time;
      // 'Precipitation': 12,
      d.Precipitation = +d.Precipitation;
      // 'Flow': 13,
      d.Flow = +d.Flow;
      // 'Stage': 15
      d.Stage = +d.Stage;
    });

    //********* - START TABLE - *********

    var sortAscending = true;
    var table = d3.select('#page-wrap').append('table');
    var titles = d3.keys(data[0]);
    // var titles = ["raceplace", "name", "club", "clocktime", "category", "handicap", "racetime", "timeplace", "points"]
    var titles = ['ID', 'Time', 'Precipitation', 'Flow', 'Stage']
    var headers = table.append('thead').append('tr')
      .selectAll('th')
      .data(titles).enter()
      .append('th')
      .text(function(d) {
        return d
      })
      .on('click', function(d) {
        headers.attr('class', 'header');
        // if (d == "name" || d == "club" || d == "category") { //these keys sort alphabetically
        //   // sorting alphabetically");
        //   if (sortAscending) {
        //     rows.sort(function(a, b) {
        //       return d3.ascending(a[d], b[d]);
        //     });
        //     sortAscending = false;
        //     this.className = 'aes';
        //   } else {
        //     rows.sort(function(a, b) {
        //       return d3.descending(a[d], b[d]);
        //     });
        //     sortAscending = true;
        //     this.className = 'des';
        //   }
        // } else {
        if (sortAscending) {
          //all other keys sort numerically including time
          rows.sort(function(a, b) {
            return b[d] - a[d];
          });
          sortAscending = false;
          this.className = 'aes';
        } else {
          rows.sort(function(a, b) {
            return a[d] - b[d];
          });
          sortAscending = true;
          this.className = 'des';
        }
        // }
      });

    var rows = table.append('tbody').selectAll('tr')
      .data(data).enter()
      .append('tr');
    rows.selectAll('td')
      .data(function(d) {
        return titles.map(function(key, i) {
          return {
            'value': d[key],
            'name': d
          };
        });
      }).enter()
      .append('td')
      .attr('data-th', function(d) {
        return d.name;
      })
      .text(function(d) {
        console.log("typeof(" + d.value + "): " + typeof(d.value));
        if (typeof(d.value) == "object") {
          return timeformat(d.value)
        } else {
          return d.value
        }
      });

    //********* - END TABLE - *********
  </script>
</body>