将for循环的值赋给函数d3

Give value of for loop to function d3

本文关键字:函数 d3 for 循环      更新时间:2023-09-26

我试图给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;
                       });

我认为你的错误在于:

.on("click", function(d, z){
    blueLine = catlist[z];

在函数中定义z将赋予它与for迭代的值不同的含义。尝试以下操作:

.on("click", function(d){
    blueLine = catlist[z];
正如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));
    }
}