寻找selectAll类似的操作,将包括在选择中调用对象(每当它匹配选择器) [英] Looking for selectAll-like operation that will include calling object in the selection (whenever it matches the selector)
问题描述
d3.js表达式
d3.select(foo).selectAll(some_selector)
将返回包含 但是假设 这个问题的以下天真的解决方案 不正确 ,因为一般来说,由此产生的选择将包含同义满足 foo $ c的所有 strict
foo
本身满足 some_selector
。
d3.select(foo.parentNode).selectAll(some_selector)
$ b b some_selector
/暂时标记所有候选元素,即foo及其所有后代
d3.select(foo).classed('yuk',true)
.selectAll('*')。classed('yuk' ,true);
var parent = d3.select(foo.parentNode),
wanted = parent.selectAll(some_selector)
.filter('。yuk');
//撤消标记
parent.selectAll('。yuk')。classed('yuk',false);您的问题解决的问题与
http://stackoverflow.com/questions/29056168/how-to-generate-a-d3-selection-consisting-exactly-of-a-dom-element-and-all-its-d\">另一个您昨天发布,虽然不是一个确切的重复。我的回答可以解决这个问题。我已调整我的 JSFiddle ,以允许对节点及其后代进行一些过滤: var selector =.foo,
x = d3.select(#x); //父节点
//获取节点x的所有子节点作为NodeList并转换为Array。
var xAndDescendants = Array.prototype.slice.call(
x.node()。querySelectorAll(selector)
);
//如果selector为true,则将节点x添加到开头。
if(!(x = x.filter(selector))。empty())
xAndDescendants.unshift(x.node());
//通过d3.js选择结果数组
var selection = d3.selectAll(xAndDescendants);
The d3.js expression
d3.select(foo).selectAll(some_selector)
will return a selection comprising all the strict descendants of foo
that satisfy some_selector
.
But suppose that foo
itself satisfies some_selector
. How can I get it included in the resulting selection when this is the case?
The following naive solution to this problem
d3.select(foo.parentNode).selectAll(some_selector)
is incorrect, because, in general, the selection resulting from it will include any siblings of foo
that satisfy some_selector
!
IOW, I'm looking for a solution that is clearer, more concise, and less of a dirty hack than this (for example):
// temporarily tag all candidate elements, namely, foo and all its descendants
d3.select(foo).classed('yuk', true)
.selectAll('*').classed('yuk', true);
var parent = d3.select(foo.parentNode),
wanted = parent.selectAll(some_selector)
.filter('.yuk');
// undo the tagging
parent.selectAll('.yuk').classed('yuk', false);
Your question addresses the same issue as the other one you posted yesterday, although not being an exact duplicate. My answer to that one will work for this problem as well. I have adjusted my JSFiddle to allow for some filtering on the node and its descendants:
var selector = ".foo",
x = d3.select("#x"); // your parent node
// Get all children of node x regarding selector as NodeList and convert to Array.
var xAndDescendants = Array.prototype.slice.call(
x.node().querySelectorAll(selector)
);
// Add node x to the beginning if selector is true.
if (!(x = x.filter(selector)).empty())
xAndDescendants.unshift(x.node());
// Select resulting array via d3.js
var selection = d3.selectAll(xAndDescendants);
这篇关于寻找selectAll类似的操作,将包括在选择中调用对象(每当它匹配选择器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!