了解 D3.js 如何将数据绑定到节点 [英] Understanding how D3.js binds data to nodes

查看:38
本文介绍了了解 D3.js 如何将数据绑定到节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 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; });

我理解大部分内容,但是 var td 语句的 .data(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 创建了一堆 元素,数组中的每个条目一个.更重要的是,它还将数组中每个条目的数据与该 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆