在d3.js中传递给事件处理程序的常量索引

在d3.js中传递给事件处理程序的常量索引,d3.js,D3.js,我在D3代码中处理事件处理程序时遇到困难:重构之前,它按预期工作: choice_groups .append("span") .attr("class", "repeat-choice") .text("Modifica questa scelta") .on("click", repeat_choice); 调用repeat_choice()函数时,单击了span.repeat-choice元素的index i参数 由于我只想将此事件处理程序附加到包含多个嵌套数据元素的元素

我在D3代码中处理事件处理程序时遇到困难:重构之前,它按预期工作:

choice_groups
  .append("span")
  .attr("class", "repeat-choice")
  .text("Modifica questa scelta")
  .on("click", repeat_choice);
调用repeat_choice()函数时,单击了span.repeat-choice元素的index i参数

由于我只想将此事件处理程序附加到包含多个嵌套数据元素的元素,因此我对上述代码进行了如下重构:

choice_groups
  .each(function(d, i) {
    if(d.length > 1) {
      d3.select(this)
        .append("span")
        .attr("class", "repeat-choice")
        .text("Modifica questa scelta")
        .on("click", repeat_choice);
    } else {
      d3.select(this)
        .append("span")
        .attr("class", "no-choice")
        .html(" ");
    }
  });
但是,repeat_choice()处理程序函数现在总是在i=0时被调用,无论单击的元素的索引是什么

我想我没有正确使用选择。each()正确:结果标记与预期一样(与重构之前一样),只有click handler函数没有通过元素的索引。

您的内部d3。select()正在创建新选择,因此每次都重置I=0(在该选择的上下文中)。您可以有条件地设置属性:

choice_groups
  .append("span")
  .attr("class", function(d,i) { return d.length > 1 ? "repeat-choice" : "no-choice"; })
  .text(function(d,i) { return d.length > 1 ? "Modifica questa scelta" : null; });
或者可能只重新选择“重复选择”元素,然后绑定单击处理:

choice_groups
    .filter(function(d,i){ return d.length > 1;})
    .on("click", repeat_choice);
(我认为,我传递给repeat_的选择也将只计算第二个选择中的过滤元素)

希望有帮助