D3.js 带更新的嵌套选择

D3.js 带更新的嵌套选择,d3.js,D3.js,我已经构建了我认为最新的解决方案,用于具有的 但是,每次单击“更新”时,我总是得到外部选择,但不总是内部嵌套选择。控制台日志显示格式正确的数组 这是v5中嵌套选择的正确设置吗? .外部{ 边框:1px纯黑; 背景颜色:灰色; 宽度:100%; 高度:100px; 位置:相对位置; 显示器:flex; } .内部{ 显示器:flex; 调整内容:灵活启动; 边框:1px纯蓝色; 背景色:青色; 宽度:50px; 高度:50px; 位置:相对位置; } 使现代化 const updateButt

我已经构建了我认为最新的解决方案,用于具有的

但是,每次单击“更新”时,我总是得到外部选择,但不总是内部嵌套选择。控制台日志显示格式正确的数组

这是v5中嵌套选择的正确设置吗?

.外部{ 边框:1px纯黑; 背景颜色:灰色; 宽度:100%; 高度:100px; 位置:相对位置; 显示器:flex; } .内部{ 显示器:flex; 调整内容:灵活启动; 边框:1px纯蓝色; 背景色:青色; 宽度:50px; 高度:50px; 位置:相对位置; } 使现代化 const updateButton=document.getElementById'update'; 常量锚点=d3。选择“锚点”; updateButton.addEventListener'click'函数{ 使现代化 Array.from{ 长度:Math.ceilMath.random*5 },功能{ 返回数组.from{ 长度:Math.ceilMath.random*5 },功能{ 返回Math.ceilMath.random*5; }; } ; }; 函数更新数据{ const outer=anchor.selectAll'.outer'.datadata; 外部退出,移除; 外面,进来 .附加'div' .合并外部 .attrclass,外部; const inner=outer.selectAll'.inner'.datafunctiond{ 返回d; }; 内部。退出。移除; 进入 .附加'div' .合并内部 .attrclass,内部 .textfunctiond{ 返回d; }; }
在这种情况下,您必须重新分配更新选择,因此它的引用将与enter选择合并。在这里,我将更改let的常量,以便重新分配选择:

//here is the update selection:
let outer = anchor.selectAll('.outer').data(data);

//here is the enter selection:
const outerEnter = outer.enter()
    .append('div')
    .attr("class", "outer");

//reassigning here: 
outer = outerEnter.merge(outer);
否则,即使在enter选择中链接了一个合并方法,other也只是更新选择。如果使用outer.size,您可以清楚地看到这一点

以下是更改后的代码:

const updateButton=document.getElementById'update'; 常量锚点=d3。选择“锚点”; updateButton.addEventListener'click'函数{ 使现代化 Array.from{ 长度:Math.ceilMath.random*5 },功能{ 返回数组.from{ 长度:Math.ceilMath.random*5 },功能{ 返回Math.ceilMath.random*5; }; } ; }; 函数更新数据{ 让outer=anchor.selectAll'.outer'.datadata; 外部退出,移除; const outerEnter=outer.enter .附加'div' .attrclass,外部; outer=outerEnter.mergeouter; const inner=outer.selectAll'.inner'.datafunctiond{ 返回d; }; 内部。退出。移除; 进入 .附加'div' .attrclass,内部 .合并内部 .textfunctiond{ 返回d; }; } .外部{ 边框:1px纯黑; 背景颜色:灰色; 宽度:100%; 高度:100px; 位置:相对位置; 显示器:flex; } .内部{ 显示器:flex; 调整内容:灵活启动; 边框:1px纯蓝色; 背景色:青色; 宽度:50px; 高度:50px; 位置:相对位置; } 使现代化