D3 - 无法在点击事件

时间:2016-03-21 18:34:46

标签: events d3.js parameters click

我试图将onClick事件添加到我的D3 barChart并执行一些操作,具体取决于点击的栏,但我无法获得该事件的数据&#39 ;参数(未定义)。我错过了什么吗?提前谢谢!

    var data = [{
        letter: 'A',
        frequency: 5
    }, {
        letter: 'B',
        frequency: 8
    }];

    var margin = {
            top: 20,
            right: 20,
            bottom: 30,
            left: 40
        },
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(10, "%");

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


    d3.select("body").on('click', function(d, i) {
            console.log(d);
            console.log(i);
            console.log(d3.event);
        });




    x.domain(data.map(function(d) {
        return d.letter;
    }));
    y.domain([0, d3.max(data, function(d) {
        return d.frequency;
    })]);

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Frequency");

    svg.selectAll(".bar")
        .data(data)
        .enter().append("rect")
        .attr("class", "bar")
        .attr("x", function(d) {
            return x(d.letter);
        })
        .attr("width", x.rangeBand())
        .attr("y", function(d) {
            return y(d.frequency);
        })
        .attr("height", function(d) {
            return height - y(d.frequency);
        });

1 个答案:

答案 0 :(得分:1)

您必须将click事件绑定到条形本身,而不是页面正文。如果您将以下内容添加到代码的末尾并从正文中移除click事件,则可以正常使用。

svg.selectAll(".bar").on('click', function(d, i) {
            console.log(d);
            console.log(i);
            console.log(d3.event);
        });