Why does my saved D3 selection have no effect in some cases?

前端 未结 1 988
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 14:10

I\'m confused about how to save a D3 selection for later use. In the code below, I have a \"global\" variable for my axes, to which I save them when they are first created.

相关标签:
1条回答
  • 2021-01-16 14:34

    This code:

    gxaxis = svg.append("g").attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis)
                    .append("text")
                    .attr("class", "label")
                    .attr("x", width)
                    .attr("y", -6)
                    .style("text-anchor", "end");
    

    Creates this DOM:

    <svg>
        <...>
            <g class="x axis">
                <g class="tick">
                    <line ...>
                    <text ...>
                </g>
            </g>
        </...>
    </svg>
    

    And saves the text to the selection, because it was appended last.
    If you want the axis, save the axis to the selection before you edit the text.

    gxaxis = svg.append("g").attr("class", "x axis")
                    .attr("transform", "translate(0," + height + ")")
                    .call(xAxis);
    gxaxis.selectAll("text")
                    .attr("class", "label")
                    .attr("x", width)
                    .attr("y", -6)
                    .style("text-anchor", "end");
    
    0 讨论(0)
提交回复
热议问题