d3匹配元素id以更新现有项目

时间:2017-07-14 15:55:18

标签: d3.js

根据第一个答案,我做了更多研究,并提出了解决问题的方法。我包括更新功能:提及键入数据很有用。

function update(data) {
    var agent = canvas.selectAll(".node.agent")
        //sets all elements to false for the class before the update
        .classed("newCall", false)
       .data(data, function (d) {
           // the key is either an element id or an id from the data
           var myId = d.id ? d.id : this.id;
           //console.log("data key: " + d.id + " element id: " + this.id + " new: " + d.newCall);
           return myId;
       }).classed("newCall", function (d) {
           var f = d.newCall ? d.newCall : false;
           //console.log(this.id + " " + f )
           return f;
       });

    agent.enter().append("g")
    .classed("newCall", function (d) {

           return d.newCall ? d.newCall : false;
       });

    agent.exit().classed("newCall", function (d) {
      //  console.log(d);
        return false;
    });

};

我有这个html,由d3使用数据生成。我有另一个数据源,我想用来修改该HTML。下面是我想用来对元素进行分类的函数,这样我就可以使用css实时更改它们。我要做的是将元素的id与新数据生成的id匹配。我有函数记录画布上元素的id。我不知道如何根据传递给更新图表功能的数据来检查id。每个(d)是现有数据。数据参数是我需要输入和更新...

function updateChart(data) {

   var sel = canvas.selectAll(".agent")
        .each(function (d) {
   // these are the id's I need to check against 
   // the data                
   console.log(d3.select(this).attr("id"));


        })
};
};

我找到了这个,它帮助我迭代现有的元素:

SO link

1 个答案:

答案 0 :(得分:1)

在我看来,这是一个XY problem:您可能不需要任何繁琐的each()代码,您可以使用key function来执行您想要的操作你的data方法。

但是,由于您没有发布数据或代码的(最小)运行版本,因此我将解答有关each()方法的具体问题。

我的建议是首先获得id元素的this ...

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

...并相应地过滤data参数:

data.filter(function(d) {
    return d.id === id;
})[0]

这是一个非常基本的演示,其中圆圈的大小根据其ID进行更改:



var data = [{
  id: "foo",
  size: 20
}, {
  id: "bar",
  size: 40
}, {
  id: "baz",
  size: 10
}];

var svg = d3.select("svg");

updateChart(data);

function updateChart(data) {

  var sel = svg.selectAll(".agent")
    .each(function() {
      var id = d3.select(this).attr("id");
      d3.select(this).transition()
        .duration(1000)
        .attr("r", function() {
          return data.filter(function(d) {
            return d.id === id;
          })[0].size;
        })
    })
};

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
  <circle class="agent" id="foo" cx="50" cy="50" r="5" fill="teal"></circle>
  <circle class="agent" id="bar" cx="150" cy="50" r="5" fill="teal"></circle>
  <circle class="agent" id="baz" cx="250" cy="50" r="5" fill="teal"></circle>
</svg>
&#13;
&#13;
&#13;