在D3.js中创建"在内存中"的元素,就像jQuery一样

use*_*166 9 d3.js

而不是做

d3.select("body").append("svg")
Run Code Online (Sandbox Code Playgroud)

,大多数d3.js的例子,我想创建一个元素,而不是立即将它附加到身体或任何东西.

有点像$('<div/>')jQuery.

我怎样才能做到这一点?

min*_*omi 16

使用document.createElement()创建元素并d3照常传递给它.

在控制台中:

> a = document.createElement("div")
<div>?</div>?
> d3.select(a).append("svg")
[Array[1]]   
> a
<div>?
<svg>?</svg>?
</div>?
Run Code Online (Sandbox Code Playgroud)

  • 通过https://github.com/mbostock/d3/issues/825更正并正式发布 (4认同)

eri*_*gor 7

// create selection containing unattached div node    
var sel = d3.create('svg');  
Run Code Online (Sandbox Code Playgroud)

如果你只想要节点......

// retrieve unattached node
var node = d3.create('svg').node();
Run Code Online (Sandbox Code Playgroud)