0

在试图理解 d3 时,我看到了这条线.text(String);。我无法理解 String 应该是什么。我想它可能是一个空字符串(不),一个方法(我在 api 参考中没有看到)并思考它可能是什么。

我在下面评论了它并得到了预期的结果。我不明白什么是 String 以及它为什么起作用。有了这条线,我的 3 个方形框有文本(它是稍后将表示的数据的内部值),而注释掉它没有。

演示

html

<div class='chart' id='chart-10'/>
<script src="http://d3js.org/d3.v3.min.js"></script>

JS:

    var w = 360;
    var h = 180;
  var svg = d3.select("#chart-10").append("svg")
      .attr("width", w)
      .attr("height", h);

  var g = svg.selectAll(".data")
      .data([50,150,250])
    .enter().append("g")
      .attr("class", "data")
      .attr("transform", function(d, i) { return "translate(" + 20 * (i + 1) + ",20)"; });

  g.append("circle")
      .attr("class", "little")
      .attr("r", 1e-6);

  g.append("rect")
      .attr("x", -10)
      .attr("y", -10)
      .attr("width", 20)
      .attr("height", 20)
      .style("fill", "lightgreen")
      .style("stroke", "green");

  g.append("text")
      .attr("dy", ".35em")
      .attr("text-anchor", "middle")
;//      .text(String);


    g.attr("transform", function(d, i) { return "translate(" + 20 * (i + 1) + ",20)"; });
    g.select("rect").style("opacity", 1);
    g.select("circle").attr("r", 1e-6);

    var t = g.transition().duration(750);
    t.attr("transform", function(d, i) { return "translate(" + d + ",90)"; });
    t.select("circle").attr("r", Math.sqrt);
    t.select("rect").style("opacity", 1e-6);
4

1 回答 1

2

它看起来像String构造函数。根据d3 文档,正如马特指出的那样:

如果 value 是一个函数,则为每个选定元素(按顺序)评估该函数,传递当前数据d和当前索引i,并将 this 上下文作为当前 DOM 元素。然后使用该函数的返回值来设置每个元素的文本内容。

所以,你之前设置g.data[50,150,250]几行。每个数字都由构造函数转换为 String 对象String,返回并用作 DOM 节点的文本值。

于 2013-01-09T14:41:17.250 回答