2016-03-08 40 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"); 
} 
相關問題