D3JS选拔和课程

Fab*_*ert 3 d3.js

是否有一种简单的方法来扩展下面的代码,以便div.someclass在不存在时自动创建?

d3.select("body").select("div.someclass").selectAll("p")
    .data([ 1, 2, 3 ])
    .enter()
        .append("p")
        .text(function (d, i) {
            return "index: " + i + ", value: " + d;
        });
Run Code Online (Sandbox Code Playgroud)

我还处于学习D3JS的早期阶段.我对它的理解至今是"而不是告诉D3如何做,你告诉D3你想要什么".所以我很惊讶地看到上面的代码需要<div class="someclass"></div>在HTML中声明.

另一种方法是以编程方式插入div:

/** Append HTML placeholder programmatically **/
placeholder = d3.select("body").append("div").attr("class", "someclass");

/** Bind the data to the DOM **/
/** instead of telling D3 how to do something, tell D3 what you want: in the absence of <p>, this will return a virtual selection **/
placeholder.selectAll("p")
    .data([ 1, 2, 3 ])
    .enter()
        .append("p")
        .text(function (d, i) {
            return "index: " + i + ", value: " + d;
        });
Run Code Online (Sandbox Code Playgroud)

有更短/更好的方式吗?

nra*_*itz 11

如果我理解正确,你问的是如何追加div.someClassIFF它不存在.这有一个D3模式,虽然它有点奇怪:

// create a selection for the container with a static 1-element array
var container = d3.select("body").selectAll("div.someclass")
    .data([0]); 

// now add it if it doesn't exist
container.enter().append('div').attr('class', 'someclass');

// now use it for the subselection
container.selectAll("p")
    .data([1, 2, 3]);

// etc
Run Code Online (Sandbox Code Playgroud)

这里奇怪的部分是.data([0])- 0传统的,不是必需的; 这可以是任何静态单元素数组.第一次调用它时,将创建一个新元素(除非先创建其他内容div.someclass).第二次,元素已经存在,因此没有.enter()选择,并且不会再附加任何内容.

这是可重用组件中相当常见的模式,可以在更新时重复调用 - 请参阅d3.svg.axis代码示例.