问题
I am trying to complete a timeline application - - but I am getting a malfunction with the region key area
latest fiddle https://jsfiddle.net/fqn4vb90/2/
when this gets rendered -- they all seem to be duplicates of the first array element? So in this example -- first element is JA, the second should be AS, and the third should be E
let listRegions = [{
"label" : "A",
"value" : "SIEA"
},{
"label" : "E",
"value" : "SIEE"
},{
"label" : "JA",
"value" : "SIEJA-JAPAN"
},{
"label" : "AS",
"value" : "SIEJA-ASIA"
}];
//reg
regions.forEach(function(entry) {
//const regions6 = ["SIEJA-ASIA", "SIEE"];
const legendRegions = listRegions.map(region => (
{
...region,
enabled: entry === region.value
})
);
console.log("legendRegions", legendRegions);
buildKey(legendRegions)
});
function buildKey(data){
console.log("DATA", data);
reg
.selectAll('.laneKeyText')
.data(data)
.enter()
.append('text')
.text(function(d) {
return d.label;
})
.style("fill", function(d, i) {
if(d.enabled){
return '#0072ce';
}
return '#D8D8D8';
})
.attr('x', function(d, i) {
return (i * 25);
})
.attr('dy', 5)
.attr('dx', 3)
.attr('text-anchor', 'start')
.attr('class', 'laneKeyText');
reg
.selectAll(".laneKeyRect")
.data(data)
.enter()
.append("rect")
.attr('x', function(d, i) {
return (i * 25);
})
.attr('y', -10)
.attr("width", 20)
.attr("height", 20)
.style("fill", "none")
.style("stroke", "#D8D8D8")
.attr('class', 'laneKeyRect');
}
回答1:
The problem here is in the following code:
...
function buildKey(data){
reg
.selectAll('.laneKeyText')
.data(data)
.enter()
.append('text')
...
Everytime you call buildKey
inside foreach
function you are sending the whole data and do a select on all text tags elements, first time text tags are created, but after that they are being selected for data rebind and then activate the current enabled element, which is different each iteration call, and the current active will be same for all selected text tags in which the all have the same class .laneKeyText
.
I added here a way to fix it but I'm sure there is a cleaner way to fix it:
https://jsfiddle.net/mamounothman/9fp8oehj/37/
来源:https://stackoverflow.com/questions/59936414/d3js-error-in-rendering-a-legend-key-duplicated-render