不更新 .each 函数中的 D3.js 元素

doesn't update d3.js elements in .each function

本文关键字:D3 js 元素 更新 each 函数      更新时间:2023-09-26

我的代码可以工作,它向我显示了数据的元素,但是在更改数据并再次运行相同的代码后,d3 不会更新我的 SVG 元素的文本。我必须刷新整个网站才能更改。

var blackbox= d3.select("#content")
                            .selectAll(".silencer")
                            .data([0]);
                blackbox.enter()
                    .append("div")
                    .attr("class", "silencer")
                    .attr("id", "silencer");
                    blackbox.exit().remove();
                    var box = blackbox.selectAll(".ursa")
                    .data(fraung);
                    box.enter()
                    .append("div")
                    .attr("class", "ursa")                      
                    .each(function(d) {
                        d3.select(this)
                        .append("svg")                  
                        .attr("class", "invoker")                           
                        .each(function(d) {

                            d3.select(this).append("svg:image")
                                .attr("xlink:href", "images/qwer.png")
                                .attr("x", "0")
                                .attr("y", "0")
                                .attr("width", "100")
                                .attr("height", "100")
                                .append("title")
                                .text(function(d) {return (d.name)});   
                        });
                        d3.select(this).append("div")
                        .attr("class", "chen")              
                        .each(function(d) {

                            d3.select(this).append("table")
                            .attr("class", "tab")
                            .each(function(d) {
                                d3.select(this).append("tbody")
                                .each(function(d) {
                                    d3.select(this).append("tr")
                                    .text(function(d) {return("Name: ")})
                                    .attr("class", "key")
                                    .each(function(d) {
                                        d3.select(this).append("td")
                                        .text(function(d) {return (d.name)});
                                    });
                                }); 
                            });
                        }); 
                }); 
                box.exit().remove();

听起来在加载第二个数据集之前,您的 SVG 元素没有被清除,因此第二个数据集被绘制在第一个数据集后面。如果唯一改变的是文本,那么看起来什么都没有发生。浏览器刷新将清除任何动态绘制的内容。在调用"黑盒"之前,您可以执行类似操作来清除"#content"元素中的所有内容,我假设该元素是您的SVG容器。

if(!d3.select("#content").empty()) d3.select("#content").remove();

这将完全删除 SVG 容器。因此,您必须先再次创建它,然后才能加载新数据。或者,如果您只想从 SVG 容器中删除子元素,则可以执行以下操作:

if(!d3.select("#content").selectAll("*").empty()) d3.select("#content").selectAll("*").remove();