D3.js svg元素遍历

时间:2013-06-24 20:08:51

标签: d3.js

//build legend key
        var svgContainer = d3.select("#TMLegend").append("svg")
              .attr("width", 972)
              .attr("height", 30);
        var width = 35, height = 10, x = 0;

        for(var e =0; e < root.children.length; e++){           
           svgContainer
              .append("rect")
              .attr("x", 0)
              .attr("y", 10)
              .attr("width", width)
              .attr("height", height)
              .attr("transform", "translate("+(36*x++)+",0)")
              .style("fill", function(){
                return colorArr[root.children[e].name];
              })
              .attr("title", function(){
                return root.children[e].name;
              })

              .text(function(){
                return root.children[e].name;
              });  
        }
d3.selectAll("#TMLegend rect").on("mouseover",function () {
        var title = d3.select(this).text();
        $("#TMLegendPopUp").show().html("<h4>"+title+"</h4>");
          //Popoup position
         $(document).mousemove(function(e){
             var popLeft = e.pageX + 10;
             var popTop = e.pageY + -90;
             $("#TMLegendPopUp").css({"left":popLeft,"top":popTop});
             $("#TMLegendPopUp h4").css({"background": colorArr[title], "margin":0});
        });    
    });

上面的代码是我尝试将id为TMLegend的div作为目标,并尝试向下钻取到svg:rect.attr('id')以获取rect元素id的内容。从那时起,我已经取消了放置ID Attr(),现在我的目标是文本()。当rect节点是硬编码时,此代码有效,但是当我使用D3生成它们时,此代码不起作用。有没有人有办法动态地用D3获取rect元素的文本?

硬编码的html如下所示:

        <div id="TMLegend">
       <svg width="972" height="30">      

农产品 宝石和宝石金属 矿物制品 建筑材料 纺织品                   非常感谢。

1 个答案:

答案 0 :(得分:0)

这与预期的一样,d3.select仅选择第一个匹配的元素。您需要使用d3.selectAll选择图例中的所有矩形,然后使用d3.select(this)将鼠标悬停在每个矩形上。基于我认为你想要完成的事情,你需要类似的东西:

d3.selectAll("#TMLegend rect").on("mouseover",function () { 
  $("#TMLegendPopUp").show()
    .html("<h4 style='margin:0'>" + d3.select(this).attr("id") + "</h4>");

    //Popoup position
   $(document).mousemove(function(e){
       var popLeft = e.pageX + 10;
       var popTop = e.pageY + -90;
       $("#TMLegendPopUp").css({"left":popLeft,"top":popTop});
   }); 
});