D3中selection之使用

1. 极为重要的reference:

[1] How selections works. http://bost.ocks.org/mike/selection/

[2] Nested selections. http://bost.ocks.org/mike/nest/

2. 相关概念笔记

(1)Selections are usually seen as arrays of DOM elements, but it is not very accurate. There are two main reasons for this:

For one, selections are asubclass of array; this subclass provides methods to manipulate selected elements, such as settingattributes and styles. Selections inherit native array methods as well, such as array.forEach andarray.map. However, you won’t often use native methods as D3 provides convenient alternatives, such as selection.each. (A few native methods are overridden to adapt their behavior to selections, namely selection.filter and selection.sort.)

Another reason selections aren’t literally arrays of elements is that they are arrays of arrays of elements: a selection is an array of groups, and each group is an array of elements. For example,d3.select returns a selection with one group containing the selected element:

var selection = d3.select("body");

In the JavaScript console, try running this command and inspecting the group as selection[0]and the node as selection[0][0].

 

(2) 一般的数据绑定的方式:先selectAll再data绑定。

var selection = d3.selectAll("div").data("numbers");

(3) Nested selection 能够保留原有dom element的hierarchical structure.

例如,对于如下中的html的DOM structure,

<table>
  <thead>
    <tr><td>  A</td><td>  B</td><td>  C</td><td>  D</td></tr>
  </thead>
  <tbody>
    <tr><td>  0</td><td>  1</td><td>  2</td><td>  3</td></tr>
    <tr><td>  4</td><td>  5</td><td>  6</td><td>  7</td></tr>
    <tr><td>  8</td><td>  9</td><td> 10</td><td> 11</td></tr>
    <tr><td> 12</td><td> 13</td><td> 14</td><td> 15</td></tr>
  </tbody>
</table>
var td = d3.selectAll("tbody td"); 

只能返回如下结构: 

Flat selections lack hierarchical structure: the table cells are merged into a single array, rather than grouped by parent row. This makes them more difficult to manipulate on a row- or column-basis. In contrast, D3’s nested selections retain the hierarchy

但是nested selections: 

var td = d3.selectAll("tbody tr").selectAll("td");

则能够返回如下的结构:

(4)如何绑定一个matrix而不是单纯的array?

var matrix = [
  [ 0,  1,  2,  3],
  [ 4,  5,  6,  7],
  [ 8,  9, 10, 11],
  [12, 13, 14, 15],
];

var body = d3.select("body");
var table = body.append("table");
var tr = table.selectAll("tr")
    .data(matrix)
  .enter().append("tr");
var td = tr.selectAll("td")
    .data(function(d) { return d; })
  .enter().append("td");

  





原文地址:https://www.cnblogs.com/jiayouwyhit/p/4999389.html