在D3中选择SVG

时间:2014-01-15 19:39:02

标签: svg d3.js

我有一点可视化,我有成对的矩形。每对共享相同的id属性。所以目前,我已经设置好了,如果我将鼠标悬停在任何一个上面,两者都会改变颜色。这很棒,但是,正如我已经完成的那样,我需要为每个不同的对选择一个新的选择(" svg #whatever)命令。那不是对的。

所以我在想的是设置一个变量,这个变量就是我把它放在一边的元素的id,然后把它放在selct命令中,就像这样

    svg.selectAll("rect")
.on("mouseover", function(d) {

var thisid = d3.select(this).attr("id")

     svg.selectAll("svg #"+thisid+)             
    .attr("fill", "red")

除非不起作用。它只是语法 - 即我有+ +错误 - 或者我在这里犯了一个根本错误?

1 个答案:

答案 0 :(得分:1)

您的想法很好,但正如Robert Longson指出的那样,您无法使用id链接两个相关对象,因为id必须对整个网页都是唯一的。

但是,您可以向数据元素添加任何属性(id除外),最好使用以"data-"开头的属性名称,然后使用CSS attribute selector找到具有相同属性的其他元素。像这样:

//when you create the rectangles:
rect.attr("data-id", function(d) { 
                   return d.id;/* or however you figure out this id */
           });


//Your event handler
svg.selectAll("rect")
  .on("mouseover", function(d) {

      var thisid = d3.select(this).attr("data-id")

      svg.selectAll("svg rect[data-id='" + thisid + "']")
                 //note the single quotes inside double quotes 
                 //the final selector should look like "svg rect[data-id='23']" 
            .attr("fill", "red");

     });

唯一的缺点是浏览器没有为快速访问索引所有属性,就像它们使用类名和ID一样,所以如果你有大量的矩形并快速鼠标悬停它们可能会很慢。使用类会使选择更快,但如果您有多个类,则会增加复杂性 - 您不能通过调用.attr("class")来访问您感兴趣的一个类值。但是,您可以首先重新访问用于定义data-id的数据变量。像这样:

//when you create the rectangles:
rect.attr("data-id", function(d) { 
                   return "data-rectangle " + /* any other classes you are adding, + */
                        "data-id-" + d.id;/* or however you figure out this id */
           });


//Your event handler
svg.selectAll("rect")
  .on("mouseover", function(d) {

      var thisid = d.id; /* or however you figure out this id */
         //d3 automatically passed the element's data object to your event handler

      svg.selectAll("svg rect.data-id-" + thisid)
                 //the final selector should look like "svg rect.data-id-23" 
            .attr("fill", "red");

     });