selection.node()仅返回第一个节点.我们可以从选择中获得所有节点的数组吗?
编辑添加了一些代码来帮助我们.
each()是唯一一个产生想要的输出,虽然相当冗长.sel[0]也返回一个带有DOM节点的数组,但它很hacky(取决于库的内部结构)并包含一个不需要的"parentNode"字段.// creating a selection to experiment with
var data= [1,2,3,4]
var sel = d3.select("li")
.data(data)
.enter().append("li").html(identity);
function identity(d){return d}
console.log(sel); // array[1] with array[4] with the <li>'s
// using .node()
var res1 = sel.node();
console.log(res1); // first <li> only
// using .each() to accumulate nodes in an array
var res2 = [];
function appendToRes2(){
res2.push(this);
}
sel.each(appendToRes2);
console.log(res2); // array[4] with the <li>'s (what I want)
// calling sel[0]
var res3 = sel[0];
console.log(res3); // array[4] with the <li>'s plus a "parentNode"
// @thisOneGuy's suggestion
var res4 = d3.selectAll(sel);
console.log(res4); // array[1] with array[1] with array[4] with the <li>'sRun Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>Run Code Online (Sandbox Code Playgroud)
编辑2为什么我要这样做?
要调用数组的方法一样reduce,并map在DOM节点上.D3提供filter但是要使用其他我首先需要从选择中提取节点数组.
我最初把它写成评论,但决定把它变成答案......
看起来d3 v4将包含您想要的功能.如果您不想等待,可以立即窃取实现并将其添加到选择原型中:
d3.selection.prototype.nodes = function(){
var nodes = new Array(this.size()), i = -1;
this.each(function() { nodes[++i] = this; });
return nodes;
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
d3.selection.prototype.nodes = function(){
var nodes = new Array(this.size()), i = -1;
this.each(function() { nodes[++i] = this; });
return nodes;
}
var data= [1,2,3,4]
var sel = d3.select("li")
.data(data)
.enter().append("li").html(identity);
function identity(d){return d}
console.log(sel.nodes());Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>Run Code Online (Sandbox Code Playgroud)
由于它来自@mbostock,所以最好的实施方案是一个很好的选择.