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

时间:2015-11-25 18:18:03

标签: javascript html d3.js

我需要使用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元素。

我该怎么做?非常感谢你

1 个答案:

答案 0 :(得分:2)

您可以使用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以编程方式构建输出。

希望这有帮助。