Javascript 对现有数据进行操作
我有一些类似这样的代码:Javascript 对现有数据进行操作,javascript,d3.js,Javascript,D3.js,我有一些类似这样的代码: 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
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的所有数据,这些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();
};
更新