我想使用以下代码绘制一些带有阴影的单词:
function myText(g, data)
{
const update = g.selectAll('g').data(data, d => d.id);
const enter = update.enter().append('g');
// bottom element
enter.append('text')
.text(d => d.text)
.attr('fill', 'grey')
.attr('x', (d, i) => 40 * i + 100)
.attr('y', 100);
// top element
enter.append('text')
.text(d => d.text)
.attr('fill', 'red')
.attr('x', (d, i) => 40 * i + 99)
.attr('y', 99);
const all = update.merge(enter);
all.select('text').text(d => d.text);
const exit = update.exit();
exit.remove();
}
const g = d3.select( ... ) // some level in scene
.append('g');
const d1 =
[
{ id: 1, text: 'a' },
{ id: 2, text: 'b' },
{ id: 3, text: 'c' }
];
const d2 =
[
{ id: 1, text: 'one' },
{ id: 2, text: 'two' },
{ id: 5, text: 'five' }
];
myText(g, d1);
myText(g, d2);
myText
的逻辑来自 Mike Bostock 的 Block "General Update Pattern, II" 。
然后我得到了这些元素:
g
|
|- g
| |- text 'one'
| |- text 'a' <- not updated, expecting 'one'
|
|- g
| |- text 'two'
| |- text 'b' <- not updated, expecting 'two'
|
|- g
|- text 'five'
|- text 'five'
我尝试过“selectAll in every”等,但也不起作用。
最佳答案
当尝试更新文本时,您实际上永远不会更新与其绑定(bind)的任何数据。相反,您正在更新绑定(bind)到父组的数据,这工作正常,但永远不会传播到其已经存在的子元素。
数据传播在 appending 时有效新元素(强调我的):
Each new element inherits the data of the current elements
但是,当仅执行简单的 .select()
时,数据不会被子元素继承。或 .selectAll()
:
The selected elements do not inherit data from this selection; use selection.data to propagate data to children.
这就是当您尝试设置更新选择的文本时发生的情况,即所选文本仍然绑定(bind)有旧数据。另一方面,不需要将相同的数据绑定(bind)到文本及其阴影文本;您也可以访问父级 <g>
用于此目的的数据:
all.selectAll('text')
.text(function() {
return d3.select(this.parentNode).datum().text;
});
看看这个工作演示:
function myText(g, data)
{
const update = g.selectAll('g').data(data, d => d.id);
const enter = update.enter().append('g');
// bottom element
enter.append('text')
// .text(d => d.text)
.attr('fill', 'grey')
.attr('x', (d, i) => 40 * i + 100)
.attr('y', 100);
// top element
enter.append('text')
// .text(d => d.text)
.attr('fill', 'red')
.attr('x', (d, i) => 40 * i + 99)
.attr('y', 99);
const all = update.merge(enter);
all.selectAll('text')
.text(function() {
return d3.select(this.parentNode).datum().text;
});
const exit = update.exit();
exit.remove();
}
const g = d3.select("body")
.append("svg")
.append('g');
const d1 =
[
{ id: 1, text: 'a' },
{ id: 2, text: 'b' },
{ id: 3, text: 'c' }
];
const d2 =
[
{ id: 1, text: 'one' },
{ id: 2, text: 'two' },
{ id: 5, text: 'five' }
];
myText(g, d1);
myText(g, d2);
<script src="https://d3js.org/d3.v4.js"></script>
关于javascript - 如何更新具有相同父值的同一级别中的所有现有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48634920/