如何在d3数据键功能中使用值?

时间:2019-02-27 16:53:50

标签: javascript d3.js

此问题与d3 v5有关。

D3似乎无法识别我的键功能值。例如。

// first create 5 elements
var data = d3.range(0,5);
var g = d3.select('svg')
  .append('g').selectAll("text")
  .data(data, d=>d+"_a");  // append value "a"

console.log(`new ${g.enter().size()} update ${g.size()} exit ${g.exit().size()}`);

// do some dummy stuff
g.enter()
  .append("text")
  .attr("id", d=>d+"_a");

var data = [1,2];
var g = d3.selectAll('text')
  .data(data, d=>d+"_b");  // append a different value "b"

// shouldn't this show: new 2 update 0 exit 5?
console.log(`new ${g.enter().size()} update ${g.size()} exit ${g.exit().size()}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width=100 height=100> </svg>

在定义键功能时是否可以添加“值”?还是只需要来自数据?

1 个答案:

答案 0 :(得分:0)

键功能仅用于比较。还将键函数中引用的数据与基于键函数绑定到元素的数据进行比较。 您不能在按键功能内添加值。

另请参阅: https://github.com/d3/d3-selection#selection_data

那里的官方文件说:

  

可以指定键功能来控制将哪个基准分配给   通过计算一个元素来替换默认的按索引联接   每个数据和元素的字符串标识符。此关键功能是   按顺序为每个选定元素求值   当前基准(d),当前索引(i)和当前组   (节点),以此作为当前DOM元素(nodes [i]);返回的   字符串是元素的键。然后还评估键功能   对于数据中的每个新基准,传递当前基准(d)时,   当前索引(i),以及该组的新数据,以此作为组的   父DOM元素;返回的字符串是基准的键。基准   对于给定的键,将使用匹配的键将其分配给元素。如果   多个元素具有相同的键,将重复的元素放入   进入出口选择;如果多个数据具有相同的密钥,则   重复数据被放入回车选择中。

看你的例子:

var data = d3.range(0,5);
var g = d3.select('svg')
  .append('g').selectAll("text")
  .data(data, d=>d+"_a");
// the g selection is joined with [0,1,2,3,4]
// the key function doesn't find a match with elements (there is none anyway)
// so g.enter() contains a placeholder for 5 elements
// which will be joined with 0,1,2,3,4 respectively

// do some dummy stuff
g.enter()
  .append("text")
  .attr("id", d=>d+"_a");

var data = [1,2];
var g = d3.selectAll('text')
  .data(data, d=>d+"_b");  
// now the 5 elements are joined with the Array [1,2]
// The key function looks for data which concatenated with "_b" matches
// with the data bound to the elements.
// So it essentially compares the data from the array with the data bound to the elements. 
// A simpler way to write the key function is
// .data(data, d => d)
// which is a common d3.js join pattern.
// Thus, the second and third <text> element match
// this condition and end up in the update selection 

一个有用的SO答案也在这里: d3.js data join shows strange result