D3.js如何只创建一个绑定到多个数据项的数据集的元素

D3.js How to create just 1 element that is binded to a dataset of multiple data items

本文关键字:绑定 数据项 js 元素 数据集 一个 创建 D3      更新时间:2023-09-26

我有一个包含5个对象的数据集。我为每个对象创建一个SVG,因为它们需要自己的SVG画布,因为我正在为每个对象绘制一个进度完成圆。我需要能够将我的文本元素绑定到我的数据,但是,我不想为每个对象创建5个文本元素,只想创建1个文本元素并设置文本字段以返回正确的索引。

如何让D3只绘制一个元素(但仍然绑定到我的数据),而不是为每个对象绘制一个元件。代码如下:

// Create svg for every data item
    var svg = slideContainer.selectAll("svg").data(data);
    svg.enter()
        .append("svg")
        .attr({
            "data-id": function (d, i) { return i; },
            "class": svgClass
        });
    svg.exit().remove();
    var text = svg.selectAll("text").data(data, function (d) { return d.Margin; });
    text.enter()
        .append("text")
            .attr({
                "data-id": function (d, i) { return i; }
            })
        .text(function (d) {
            return data[$(this).attr("data-id")].Margin;
        });
    text.exit().remove();
    text.transition().duration(750)
                        .attr({
                            "x": 100,
                            "y": 100,
                            "fill": "white",
                            "class": function (d) {
                                if ($(this).attr("data-id") != $(this).parent().attr("data-id")) {
                                    return "hide";
                                }
                            },
                            "id": "text"
                        })
                        .text(function (d) {
                            return d.Margin;
                        });

您所拥有的是接近的。你只需要一个容器,然后把你的svg附加到你的容器上,就像这样:

 var svgContainer = slideContainer.selectAll("svg").data(data).enter();
 var progressBar = svgContainer.append("svg")
        .attr({
            "data-id": function (d, i) { return i; },
            "class": svgClass
        });

var progressBarText = svgContainer
        .append("text")
        //and so on
svgContainer.exit().remove();

编辑

除非你想把它附加到你的进度条svg:

var progressBarText = progressBar.append('g')
            .append("text")
            //and so on. This will use the same data as the progress bar