0

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

choice_groups
  .append("span")
  .attr("class", "repeat-choice")
  .text("Modifica questa scelta")
  .on("click", repeat_choice);

在单击 span.repeat-choice 元素的索引 i 参数的情况下调用了 repeat_choice() 函数。

由于我只想将此事件处理程序附加到具有多个嵌套数据元素的元素,因此我将上面的代码重构如下:

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 时被调用,无论哪个是被点击元素的索引。

我想我没有正确使用 selection.each() :生成的标记与预期的一样(和重构之前一样),只有点击处理函数没有通过元素的索引。

4

1 回答 1

2

您的内部 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_choice 的 i 也只会计算第二次选择中的过滤元素)

希望有帮助。

于 2013-02-22T08:03:18.580 回答