D3.js d3js-如何使用'this'关键字或替代关键字是什么?
当用户单击D3.js d3js-如何使用'this'关键字或替代关键字是什么?,d3.js,D3.js,当用户单击图例时我正在隐藏并显示路径。它起作用了。但是当路径被隐藏时,我也希望将图例保持为半透明 为此,我尝试使用this关键字将样式添加到图例中,但它不起作用 正确的方法是什么?她是我的密码: legends.on('click', function(d, i) { var path = d3.select("#" + d.name); var visibility = path.style('opacity'); path.style("opacity", visib
图例时
我正在隐藏并显示路径
。它起作用了。但是当路径
被隐藏时,我也希望将图例保持为半透明
为此,我尝试使用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);
});
})
更新
单击控制台,这是:
根据我的理解,您希望将单击事件添加到图例组
追加元素时,应添加click事件。我正在添加带有虚拟数据的示例。希望这对你有帮助
HTML
<div id="chartArea"></div>
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");
}
你能发布一个JSFiddle/JSBin/。。。显示问题?这不太容易用小提琴再现,因为场景需要多个依赖项。您能通过控制台输出d
,并检查捆绑数据吗?@DavidGuan-d用我的question@3gwebtrain对不起,我说得很清楚<代码>控制台。记录中的d
。点击('click',函数(d,i)
,以确保选择正确。
//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");
}