2016-03-08 42 views
0

当用户点击legend我隐藏并显示path。有用。但是,我想保持legend半透明,当path被隐藏。d3js - 如何使用`this`关键字或替代项是什么?

为此,我试图使用this关键字将样式添加到legend,但它不起作用。

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

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

+0

你能发布的jsfiddle/JSBin/...出的问题? –

+0

由于场景需要多个依赖项,所以这不太容易在小提琴中重现 – 3gwebtrain

+0

您可以通过控制台输出'd'并检查捆绑的数据吗? –

回答

1

根据我的理解,你想添加点击事件传说组。

当你追加元素时,你应该添加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"); 
} 
相关问题