【发布时间】:2018-08-08 14:52:13
【问题描述】:
我有一堆附加到 DOM 元素的数据,我想将每个数据加倍。我天真的方法是将它们全部选中并在选择时使用函数调用数据。我认为这已经足够了,因为数据存储在元素上,而不是选择本身。
但是,这根本不符合我的要求。奇怪的是,它会导致选择数据[undefined] 而不是[2, 4, 6],并且不会影响附加到元素的数据。更奇怪的是,如果我用身份函数调用它,我会得到一个异常:Cannot read property 'length' of undefined
这里发生了什么? D3 是否只允许使用 enter/exit 选择上的函数调用 data?
// Create a bunch of elements with attached data.
const selection = d3.selectAll('p').data([1,2,3]).enter().append('p');
console.log(selection.data());
// This doesn't work, but seems like it should:
selection.data(d => d * 2);
console.log(selection.data());
// This throws an exception??
selection.data(d => d);
console.log(selection.data());
// Is this the simplest way that works?
selection.data(selection.data().map(d => d * 2));
console.log(selection.data());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
【问题讨论】:
标签: d3.js