了解D3.js如何将数据绑定到节点 [英] Understanding how D3.js binds data to nodes
问题描述
我正在阅读D3.js文档,发现很难理解文档中的 selection.data
方法。
I'm reading through the D3.js documentation, and am finding it hard to understand the selection.data
method from the documentation.
这是文档中给出的示例代码:
This is the example code given in the documentation:
var matrix = [
[11975, 5871, 8916, 2868],
[ 1951, 10048, 2060, 6171],
[ 8010, 16145, 8090, 8045],
[ 1013, 990, 940, 6907]
];
var tr = d3.select("body").append("table").selectAll("tr")
.data(matrix)
.enter().append("tr");
var td = tr.selectAll("td")
.data(function(d) { return d; })
.enter().append("td")
.text(function(d) { return d; });
我了解大部分内容,但是 .data
? var td
语句的语句(function(d){return d;})
I understand most of this, but what is going on with the .data(function(d) { return d; })
section of the var td
statement?
我最好的猜测如下:
-
var tr
语句将四元素数组绑定到每个tr节点 -
var td
语句然后使用四元素数组作为其数据
- The
var tr
statement has bound a four-element array to each tr node - The
var td
statement then uses that four-element array as its data, somehow
但是 .data(function(d){return d;})
实际获取数据,它返回什么?
But how does .data(function(d) { return d; })
actually get that data, and what does it return?
推荐答案
写下:
….data(someArray).enter().append('foo');
D3会创建一堆< foo>
元素,一个用于数组中的每个条目。更重要的是,它还将数组中每个条目的数据与该DOM元素作为 __ data __
属性相关联。
D3 creates a bunch of <foo>
elements, one for each entry in the array. More importantly, it also associates the data for each entry in the array with that DOM element, as a __data__
property.
尝试此操作:
var data = [ {msg:"Hello",cats:42}, {msg:"World",cats:17} ];
d3.select("body").selectAll("q").data(data).enter().append("q");
console.log( document.querySelector('q').__data__ );
你将看到(在控制台中)是 {msg: Hello,cats:42}
,因为它与第一个创建的 q
元素相关联。
What you will see (in the console) is the object {msg:"Hello",cats:42}
, since that was associated with the first created q
element.
如果你以后做:
d3.selectAll('q').data(function(d){
// stuff
});
d
的值为 __ data __
属性。 (在这一点上,您可以确保用代码返回 // stuff
)。
the value of d
turns out to be that __data__
property. (At this point it's up to you to ensure that you replace // stuff
with code that returns a new array of values.)
这是另一个示例,显示绑定到HTML元素的数据和能够重新绑定较低元素上的数据子集:
Here's another example showing the data bound to the HTML element and the ability to re-bind subsets of data on lower elements:
这篇关于了解D3.js如何将数据绑定到节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!