d3 onclick获取特定的路径/条引用

时间:2017-04-12 13:34:33

标签: d3.js dc.js crossfilter

如果我有d3 / dc图表,我设置了一个像这样的点击事件处理程序:

    var data = [{
    "city": "New York",
        "neighborhood": "N/A",
        "hits": 200
}, {
    "city": "New York",
        "neighborhood": "Brooklyn",
        "hits": 225
}, {
    "city": "New York",
        "neighborhood": "Queens",
        "hits": 1
}, {
    "city": "San Francisco",
        "neighborhood": "Chinatown",
        "hits": 268
}, {
    "city": "San Francisco",
        "neighborhood": "Downtown",
        "hits": 22
}, {
    "city": "Seattle",
        "neighborhood": "N/A",
        "hits": 2
}, {
    "city": "Seattle",
        "neighborhood": "Freemont",
        "hits": 25
}];
var pieChart = dc.pieChart("#pieChart"),
    rowChart = dc.rowChart("#rowChart");
var ndx = crossfilter(data),
    cityDimension = ndx.dimension(function (d) {
        return d.city;
    }),
    cityGroup = cityDimension.group().reduceSum(function (d) {
        return d.hits;
    }),
    neighborhoodDimension = ndx.dimension(function (d) {
        return d.neighborhood;
    }),
    neighborhoodGroup = neighborhoodDimension.group().reduceSum(function (d) {
        return d.hits;
    });

pieChart.width(200)
    .height(200)
    .slicesCap(4)
    .dimension(cityDimension)
    .group(cityGroup);
pieChart.filter = function() {};

    var colorScale = d3.scale.ordinal()
            .domain(["San Francisco", "New York", "Seattle"])
            .range(["#D82C8C", "#17A7CF", "#E58304"]);

    pieChart.colors(colorScale);

rowChart.width(500)
    .height(500)
    .dimension(neighborhoodDimension)
    .group(neighborhoodGroup);

dc.renderAll();

var clickChart = d3.select("#pieChart")
clickChart.on("click",function(e){
      console.log(this)
      console.log(d3.select(this.parentNode))
})

我正在尝试找到一种方法来引用我点击的特定路径/栏/等。因此,在小提琴示例中,我希望能够抓住我点击的城市,这可能吗?

JSFiddle

1 个答案:

答案 0 :(得分:2)

而不是选择<div>,只需选择路径并获取&#34中的数据(第一个参数);点击&#34;功能:

var clickChart = d3.selectAll("path").on("click", function(e) {
    console.log(e.data.key)
})

这是你的小提琴:http://jsfiddle.net/1sbrng9n/