我正在尝试为d3的点击功能提供for循环的值。不幸的是,没有任何成功。你们当中有人知道如何解决吗?这是有问题的代码:

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;
                       });

最佳答案

正如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));
    }
}

09-25 17:34