d3js - 如何使用`this`关键字或什么是替代?

时间:2016-03-08 06:46:22

标签: d3.js

当用户点击我隐藏的legend并显示path时。有用。但是,当隐藏legend时,我希望将path保持为半透明。

为此,我尝试使用legend关键字将样式添加到this,但它无效。

这样做的正确方法是什么?她是我的代码:

legends.on('click', function(d, i) {
    var path = d3.select("#" + d.name);
    var visibility = path.style('opacity');
    path.style("opacity", visibility == 1 ? 0 : 1);

    if (!visibility) {

        d3.select(this).style('opacity', 0.5);//not working!
        this.style('opacity', 0.5);//not working!

    }

});

更新

尝试这种方式仍然不起作用:

legends.forEach(function(group) {

    var legend = group;

    legend.on('click', function(d, i) { //throws error

        var path = d3.select("#" + d.name);
        var visibility = path.style('opacity');
        path.style("opacity", visibility == 1 ? 0 : 1);

        console.log(legend);

    });

})

更新

点击安慰this - 是: console

1 个答案:

答案 0 :(得分:1)

根据我的理解,您希望将click事件添加到图例组。

添加元素时应添加click事件。我正在添加虚拟数据的示例。 Here is filddle。希望这会对你有所帮助。

<强> HTML

<div id="chartArea"></div>

<强> CSS

svg {
    background-color: #fff;
}

<强> Javscritpt

//appending svg to div and adding width and height
var svg = d3.select("#chartArea").append("svg");
svg.attr({
    'width' : 350,
  'height': 150
});

//dummy data
var data = [{name: "legend1"}, {name: "legend2"}];

//appending group
var groupSelection = svg.append('g');

//appending legends
var legendSelection = groupSelection.selectAll('text')
                .data(data)
        .enter()
        .append('text')
        .attr("x", 10)
        .attr("y", function(d, i) { return (i+1) * 15;})
        .text(function(d) {return d.name;})
        .on('click', legendClickFunction);

//click event handler
function legendClickFunction(d, i) {
        console.log(this);
        //adding color to text using this selection
        d3.select(this).attr("fill", "red");
}