选择d3节点的数据

选择d3节点的数据

本文介绍了选择d3节点的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在回调中选择一个节点,而不使用 d3.select(this)

I’d like to select a node in a callback without using d3.select(this).

我有一些代码绘制饼图...

I have some code that draws a pie…

function drawPie(options) {
  options || (options = {});
  var data = options.data || [],
      element = options.element,
      radius = options.radius || 100,
      xOffset = Math.floor(parseInt(d3.select(element).style('width'), 10) / 2),
      yOffset = radius + 20;

  var canvas = d3.select(element)
              .append("svg:svg")
              .data([data])
              .attr("width", options.width)
              .attr("height", options.height)
              .append("svg:g")
              .attr("transform", "translate(" + xOffset + "," + yOffset + ")");

  var arc = d3.svg.arc()
    .outerRadius(radius);

  var pie = d3.layout.pie()
    .value(function(data) {
      return data.percentageOfSavingsGoalValuation;
    });

  var arcs = canvas.selectAll("g.slice")
    .data(pie)
    .enter()
    .append("svg:g")
    .attr("class", "slice");

  arcs.append("svg:path")
    .on("mouseover", divergeSlice);

你会注意到最后我调用 divergeSlice 。这看起来像这样:

You’ll notice at the end I have a call to divergeSlice(). That looks like this:

function divergeSlice(datum, index) {
  var angle = (datum.endAngle + datum.startAngle) / 2,
      x = Math.sin(angle) * 10,
      y = -Math.cos(angle) * 10;

  d3.select(this)
    .transition()
    .attr("transform", "translate(" + x + ", " + y + ")");
}

这样可以工作,但是我想不用 this ,正如我前面提到的。当我记录 datum 对象时,我得到如下:

This works, but I’d like to accomplish this without using this as I mentioned earlier. When I log the datum object, I get something like the following:

{
  data: {
    uniqueID: "XX00X0XXXX00"
    name: "Name of value"
    percentageOfValuation: 0.4
    totalNetAssetValue: 0
  }
  endAngle: 5.026548245743669
  innerRadius: 80
  outerRadius: 120
  startAngle: 2.5132741228718345
  value: 0.4
}

我如何使用 d3.select()找到一个拥有 datum.data.uniqueID 等于XX00X0XXXX00?

How could I use d3.select() to find a path that holds datum.data.uniqueID that is equal to "XX00X0XXXX00"?

推荐答案

直接使用 .select(),因为它使用DOM选择器。你可以做的是选择所有的候选人,然后过滤:

You can't do this directly with .select() as that uses DOM selectors. What you can do is select all the candidates and then filter:

d3.selectAll("g")
  .filter(function(d) { return d.data.uniqueID === myDatum.data.uniqueID; });

但是,将此ID作为ID分配给DOM元素基于以下选择:

However, it would be much easier to simply assign this ID as an ID to the DOM element and then select based on that:

var arcs = canvas.selectAll("g.slice")
  .data(pie)
  .enter()
  .append("svg:g")
  .attr("id", function(d) { return d.data.uniqueID; })
  .attr("class", "slice");

d3.select("#" + myDatum.data.uniqueID);

这篇关于选择d3节点的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 04:41