如何使用D3来附加几行html代码

How to use D3 to append several html line of codes

本文关键字:几行 html 代码 D3 何使用      更新时间:2023-09-26

我需要使用D3:添加所有这些代码

 <fieldset style="width: 280px; margin-left: 45px; position: absolute;" >
        <legend>Options</legend>
          <d>Rotation: </d>&nbsp;
          <select id="rotation" style="position: center;">
          </select>  &nbsp; 
          <d>Inclination: &nbsp;</d>
          <select id="inclination" style="position: center;">
          </select>
     </fieldset>

我需要D3的原因是,我只想在某个任务完成后添加这段代码,并且只想在完成后填充两个Select元素。

我该怎么做?非常感谢

您可以使用d3.html()

首先选择要放置控件的出口,然后使用html方法插入控件。

d3.select('#where-you-want-the-output').html('<fieldset style="width: 280px; margin-left: 45px; position: absolute;" ><legend>Options</legend><d>Rotation: </d>&nbsp;<select id="rotation" style="position: center;"></select>  &nbsp; <d>Inclination: &nbsp;</d><select id="inclination" style="position: center;"></select></fieldset>');

如果您想在源代码中保留格式,可以使用'生成多行字符串。

d3.select('body').html(
'<fieldset style="width: 280px; margin-left: 45px; position: absolute;" > '
  <legend>Options</legend> '
    <d>Rotation: </d>&nbsp; '
    <select id="rotation" style="position: center;"> '
 '
    </select>  &nbsp; '
    <d>Inclination: &nbsp;</d> '
    <select id="inclination" style="position: center;"> ]
 '
    </select> '
</fieldset>');

如果您为d3.html提供一个参数,它将为该选择设置html,但如果您在没有参数的情况下调用它,它将返回已经存在的内容。所以,如果你有现有的内容,你可以把它拉成这样的字符串。。。

d3.select('#where-i-want-to-add-more-content').html(
  d3.select('#where-i-want-to-add-more-content').html() + // get what's already there...
  '<fieldset style="width: 280px; margin-left: 45px; position: absolute;" > '
    <legend>Options</legend> '
      <d>Rotation: </d>&nbsp; '
      <select id="rotation" style="position: center;"> '
   '
      </select>  &nbsp; '
      <d>Inclination: &nbsp;</d> '
      <select id="inclination" style="position: center;"> ]
   '
      </select> '
  </fieldset>'
);

不过,在这一点上,它可能会变得有点混乱,您最好为消息提供一个特定的容器,您可以随时覆盖其内容。或者使用d3.append以编程方式构建输出。

希望这能有所帮助。