如何从文本的 onclick 方法中更改 d3.js 文本输入?

Saq*_*Ali 1 javascript svg d3.js

我的 AngularJS 应用程序使用 d3.js 绘制漂亮的图表。

绘制此图表时,它使用在屏幕上绘制一些文本。当有人根据 的布尔值单击该文本时,我想更改该文本myCondition。我就是这样做的:

          var nodeEnter = node.enter()

          var myLabel = nodeEnter.append("text")
              .attr("x", 50)
              .attr("dy", "3")
              .text("Hello World")
              .style("fill-opacity", 0)
              .style("cursor", "pointer")
              .on("click", function(d) {
                  if (myCondition) 
                      myLabel.text("Mars");
                  else
                      myLabel.text("Venus");
                }
              );
Run Code Online (Sandbox Code Playgroud)

它有点有效。文本的值确实从Hello World变为MarsVenus。但有一个问题。该代码在递归函数和循环内调用。该递归+循环使用相同的代码在 SVG 容器上绘制大量此类文本。因此,当我单击此标签时,它不仅会更改我想要的文本。它还更改了其他地方的文本!我不想要这样。我该如何预防?

我真的只需要一种可以在单击功能中寻址的方法thismyself以便它知道我正在谈论该对象。如何?

Ger*_*ado 5

在不知道您的递归函数和循环的情况下,我将尝试两种不同的方法,我希望其中一种可行。

第一个用于this点击事件:

var myLabel = nodeEnter.append("text")
          .attr("x", 50)
          .attr("dy", "3")
          .text("Hello World")
          .style("fill-opacity", 0)
          .style("cursor", "pointer")
          .on("click", function(d) {
              if (myCondition) 
                  d3.select(this).text("Mars");
              else
                  d3.select(this).text("Venus");
            }
          );
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,您可以尝试为不同的myLabel文本设置特定的类。这样做,即使您myLabel的 SVG 中有多个,每个 SVG 都有一个唯一的类。假设这index是循环的特定值(如i)。所以,你可以尝试:

var myLabel = nodeEnter.append("text")
          .attr("x", 50)
          .attr("dy", "3")
          .attr("class", "myLabel" + index)//index is any value unique for the loop
          .text("Hello World")
          .style("fill-opacity", 0)
          .style("cursor", "pointer")
          .on("click", function(d) {
              if (myCondition) 
                  d3.selectAll(".myLabel" + index).text("Mars");
              else
                  d3.selectAll(".myLabel" + index).text("Venus");
            }
          );
Run Code Online (Sandbox Code Playgroud)