我正在尝试将for循环的值赋给d3的on click函数。没有任何成功,不幸的是。你们有谁知道如何解决这个问题?这是有问题的代码:
function generateLegenda(catlist) {
for (z=0; z < catlist.length ; z++) {
var legenda = d3.select("div.legendaCats")
.append("p")
.attr("class", "legendaItem")
.on("click", function(d, z){
blueLine = catlist[z];
// Determine if current line is visible
var active = (d3.selectAll("#" + blueLine)).active ? false : true,
newOpacity = active ? 0.2 : 1;
// Hide or show the elements
d3.selectAll("#" + blueLine).style("opacity", newOpacity);
d3.selectAll("#" + blueLine).style("opacity", newOpacity);
// Update whether or not the elements are active
(d3.selectAll("#" + blueLine)).active = active;
});
答案 0 :(得分:1)
我认为你的错误在于:
.on("click", function(d, z){
blueLine = catlist[z];
在函数中定义z
将赋予它不同于for迭代值的含义。请尝试以下方法:
.on("click", function(d){
blueLine = catlist[z];
答案 1 :(得分:0)
正如Giannis所提到的,函数的z
参数覆盖了for循环的z
。
但是你必须使用一个闭包来保存监听器中z
的当前值,试试这个:
function generateLegenda(catlist) {
for (z=0; z < catlist.length ; z++) {
var legenda = d3.select("div.legendaCats")
.append("p")
.attr("class", "legendaItem")
.on("click", (function(catIndex){
return function(d){
blueLine = catlist[catIndex];
// Determine if current line is visible
var active = (d3.selectAll("#" + blueLine)).active ? false : true,
newOpacity = active ? 0.2 : 1;
// Hide or show the elements
d3.selectAll("#" + blueLine).style("opacity", newOpacity);
d3.selectAll("#" + blueLine).style("opacity", newOpacity);
// Update whether or not the elements are active
(d3.selectAll("#" + blueLine)).active = active;
};
})(z));
}
}