使用"attr()"时选择之间的差异 [英] Difference between selections when using 'attr()'

查看:69
本文介绍了使用"attr()"时选择之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,单击按钮即可调用.

I have piece of code which is invoked on a button click.

const lines = svg.select('lines').selectAll('line').data(arr);
lines.enter().append('line');
lines
  .attr('x1', d => d)
  .attr('y1', d => d)
  .attr('x2', d => d+2)
  .attr('y2', d => d+2)
  .attr('stroke-width', 2);

当我单击按钮时,什么都没有显示,但是在第二次单击按钮时,可以看到线条.

And when i click the button nothing shows up, but on clicking the button for the second time the lines could be seen.

因此,我尝试仅将 .attr()链接到 .append(). 像这样:

So I tried chaining the .attr() to the .append() only. Like this:

const lines = svg.select('lines').selectAll('line').data(arr);
    lines.enter().append('line')
      .attr('x1', d => d)
      .attr('y1', d => d)
      .attr('x2', d => d+2)
      .attr('y2', d => d+2)
      .attr('stroke-width', 2);

这一次可以在第一次单击按钮时看到线条.

This time the lines could be seen on the first click of the button.

我只想知道这种行为的原因.

I just want to know the reason behind this behavior.

推荐答案

在您的第一个代码段中,您正在lines变量上执行.attr.这将保持update选择(页面上已经存在的事物的选择).由于什么都不存在,所以没有任何更新.

In your first code snippet, you are executing the .attr on the lines variable. This is holding the update selection (a selection of those things already on the page). Since nothing pre-exists, there is nothing to update.

在第二个代码段中,您正在对方法返回的事物执行.attr(通过链接).那些事物刚被.enter添加到页面中,并且是enter选择.

In the second code snippet, you are executing the .attr on the thing returned by the .append method (via chaining). Those things were just added to the page by .enter and are the enter selection.

这篇关于使用"attr()"时选择之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆