对退出数据进行操作

Operating on exiting data

本文关键字:操作 数据 退出      更新时间:2023-09-26

我有一些像这样的代码:

var data = [1,2,3,4,5,6,7,8,9,10];
var dataMap = {
    1 : 'a',
    2 : 'b',
    3 : 'c',
    4 : 'd',
    5 : 'e',
    6 : 'f',
    7 : 'g',
    8 : 'h',
    9 : 'i',
    10 : 'j'
}
var root = d3.select('#myDiv').selectAll('div').data(data, function(d){return d;})
    .enter()
    .append('div')
    .text(function(d){ return dataMap[d] });
var newData = [2,3,4,6,7,8];
var select = root.selectAll('div').data(newData, function(d){ return d; });

我需要删除不再存在的div,但首先,我需要操作与现有div相关的数据,如下所示:

exitingData.each(function(d){ dataMap.delete[d]; });

我在获得数组exitingData时遇到了麻烦,我想成为我最初绑定到我的div的所有数据的数组,其id不在新数据中。当我输入新数据时,是否有方法获取过时的数据?我试过这个,它不工作:

exit.each(function(d){ console.log(d); console.log('ran!') });

这是我正在使用的小提琴:小提琴

我相信这就是你想要的。基本上,我正在将现有div的文本打印到控制台。

function update(dataset) {
    var root = d3.select('#myDiv')
        .selectAll('div')
        .data(dataset, function(d){return d;});
    // enter selection
    root
      .enter()
        .append('div');
    // update selection
    root
        .text(function(d){ return dataMap[d] });
    // capturing the exit selection
    var rootExit = root.exit();
    // using the exit selection before removal
    // i.e. printing exiting div text to console
    rootExit.each(function(d){ console.log(d3.select(this).text()) });
    // finally removing elements
    rootExit
      .remove();
};

更新小提琴。