Skip to content

选择元素

¥Selecting elements

选择集是来自 DOM 的一组元素。Typically these elements are identified by selectors such as .fancy for elements with the class fancy, or div to select DIV elements.

¥A selection is a set of elements from the DOM. Typically these elements are identified by selectors such as .fancy for elements with the class fancy, or div to select DIV elements.

选择方法有两种形式:select 和 selectAll:前者仅选择第一个匹配的元素,而后者按文档顺序选择所有匹配的元素。顶层选择方法 d3.selectd3.selectAll 查询整个文档;子选择方法 selection.selectselection.selectAll 将选择范围限制在所选元素的后代元素上。直接子元素也有 selection.selectChildselection.selectChildren 变体。

¥Selection methods come in two forms, select and selectAll: the former selects only the first matching element, while the latter selects all matching elements in document order. The top-level selection methods, d3.select and d3.selectAll, query the entire document; the subselection methods, selection.select and selection.selectAll, restrict selection to descendants of the selected elements. There is also selection.selectChild and selection.selectChildren for direct children.

按照惯例,返回当前选择的选择方法(例如 selection.attr)使用四个缩进空格,而返回新选择的方法仅使用两个缩进空格。这有助于通过使上下文变化从链中突出来揭示上下文变化:

¥By convention, selection methods that return the current selection such as selection.attr use four spaces of indent, while methods that return a new selection use only two. This helps reveal changes of context by making them stick out of the chain:

js
d3.select("body")
  .append("svg")
    .attr("width", 960)
    .attr("height", 500)
  .append("g")
    .attr("transform", "translate(20,20)")
  .append("rect")
    .attr("width", 920)
    .attr("height", 460);

selection()

源代码 · 选择 根元素,document.documentElement

¥Source · Selects the root element, document.documentElement.

js
const root = d3.selection();

此函数还可用于测试选择(instanceof d3.selection)或扩展选择原型。例如,添加一个方法来选中复选框:

¥This function can also be used to test for selections (instanceof d3.selection) or to extend the selection prototype. For example, to add a method to check checkboxes:

js
d3.selection.prototype.checked = function(value) {
  return arguments.length < 1
      ? this.property("checked")
      : this.property("checked", !!value);
};

然后使用:

¥And then to use:

js
d3.selectAll("input[type=checkbox]").checked(true);

select(selector)

源代码 · 选择第一个与指定选择器字符串匹配的元素。

¥Source · Selects the first element that matches the specified selector string.

js
const svg = d3.select("#chart");

如果没有元素与选择器匹配,则返回空选择。如果多个元素与选择器匹配,则仅选择第一个匹配的元素(按文档顺序)。例如,选择第一个锚点元素:

¥If no elements match the selector, returns an empty selection. If multiple elements match the selector, only the first matching element (in document order) will be selected. For example, to select the first anchor element:

js
const anchor = d3.select("a");

如果选择器不是字符串,则选择指定的节点;如果你已经拥有对某个节点(例如 document.body)的引用,这将很有用。

¥If the selector is not a string, instead selects the specified node; this is useful if you already have a reference to a node, such as document.body.

js
d3.select(document.body).style("background", "red");

或者,将点击的段落设置为红色:

¥Or, to make a clicked paragraph red:

js
d3.selectAll("p").on("click", (event) => d3.select(event.currentTarget).style("color", "red"));

selectAll(selector)

源代码 · 选择所有与指定选择器字符串匹配的元素。

¥Source · Selects all elements that match the specified selector string.

js
const p = d3.selectAll("p");

元素将按文档顺序(从上到下)选择。如果文档中没有元素与选择器匹配,或者选择器为空或未定义,则返回空选择。

¥The elements will be selected in document order (top-to-bottom). If no elements in the document match the selector, or if the selector is null or undefined, returns an empty selection.

如果选择器不是字符串,则选择指定的节点数组;如果你已经拥有对节点(例如事件监听器中的 this.childNodes)或全局变量(例如 document.links)的引用,这将很有用。节点可以是可迭代对象,也可以是伪数组,例如 NodeList。例如,要将所有链接颜色设为红色:

¥If the selector is not a string, instead selects the specified array of nodes; this is useful if you already have a reference to nodes, such as this.childNodes within an event listener or a global such as document.links. The nodes may instead be an iterable, or a pseudo-array such as a NodeList. For example, to color all links red:

js
d3.selectAll(document.links).style("color", "red");

selection.select(selector) {#selection_select}

源代码 · 对于每个选定元素,选择第一个与指定选择器字符串匹配的后代元素。

¥Source · For each selected element, selects the first descendant element that matches the specified selector string.

js
const b = d3.selectAll("p").select("b"); // the first <b> in every <p>

如果没有元素与当前元素的指定选择器匹配,则返回的选择中当前索引处的元素将为空。(如果选择器为空,则返回选择项中的每个元素都将为空,从而导致选择项为空。)如果当前元素具有关联数据,则该数据将传播到相应的选定元素。如果多个元素与选择器匹配,则仅选择按文档顺序匹配的第一个元素。

¥If no element matches the specified selector for the current element, the element at the current index will be null in the returned selection. (If the selector is null, every element in the returned selection will be null, resulting in an empty selection.) If the current element has associated data, this data is propagated to the corresponding selected element. If multiple elements match the selector, only the first matching element in document order is selected.

如果选择器是一个函数,则按顺序为每个选定元素求值,传递当前数据 (d)、当前索引 (i) 和当前组 (nodes),并将其作为当前 DOM 元素 (nodes[i])。它必须返回一个元素,如果没有匹配的元素,则返回 null。例如,选择每个段落的上一个同级元素:

¥If the selector is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). It must return an element, or null if there is no matching element. For example, to select the previous sibling of each paragraph:

js
const previous = d3.selectAll("p").select(function() {
  return this.previousElementSibling;
});

Unlike selection.selectAll, selection.select does not affect grouping:它会保留现有的组结构和索引,并将数据(如果有)传播给选定的子项。分组在 数据连接 中起着重要作用。有关此主题的更多信息,请参阅 嵌套选择选择工作原理

¥Unlike selection.selectAll, selection.select does not affect grouping: it preserves the existing group structure and indexes, and propagates data (if any) to selected children. Grouping plays an important role in the data join. See Nested Selections and How Selections Work for more on this topic.

CAUTION

selection.select 将父元素的数据传播给选定的子元素。

¥selection.select propagates the parent’s data to the selected child.

selection.selectAll(selector) {#selection_selectAll}

源代码 · 对于每个选定元素,选择与指定选择器字符串匹配的后代元素。

¥Source · For each selected element, selects the descendant elements that match the specified selector string.

js
const b = d3.selectAll("p").selectAll("b"); // every <b> in every <p>

返回的选择集中的元素会根据其在此选择集中对应的父节点进行分组。如果没有元素与当前元素的指定选择器匹配,或者选择器为空,则当前索引处的组将为空。选定元素不继承此选择集的数据;使用 selection.data 将数据传播给子节点。

¥The elements in the returned selection are grouped by their corresponding parent node in this selection. If no element matches the specified selector for the current element, or if the selector is null, the group at the current index will be empty. The selected elements do not inherit data from this selection; use selection.data to propagate data to children.

如果选择器是一个函数,则按顺序为每个选定元素求值,传递当前数据 (d)、当前索引 (i) 和当前组 (nodes),并将其作为当前 DOM 元素 (nodes[i])。它必须返回一个元素数组(或一个可迭代对象,或一个伪数组,例如 NodeList),如果没有匹配的元素,则返回空数组。例如,选择每个段落的前后同级元素​​:

¥If the selector is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). It must return an array of elements (or an iterable, or a pseudo-array such as a NodeList), or the empty array if there are no matching elements. For example, to select the previous and next siblings of each paragraph:

js
const sibling = d3.selectAll("p").selectAll(function() {
  return [
    this.previousElementSibling,
    this.nextElementSibling
  ];
});

Unlike selection.select, selection.selectAll does affect grouping:每个选定的后代元素都按原始选择中的父元素分组。分组在 数据连接 中起着重要作用。有关此主题的更多信息,请参阅 嵌套选择选择工作原理

¥Unlike selection.select, selection.selectAll does affect grouping: each selected descendant is grouped by the parent element in the originating selection. Grouping plays an important role in the data join. See Nested Selections and How Selections Work for more on this topic.

selection.filter(filter) {#selection_filter}

源代码 · 过滤选择内容,返回一个仅包含指定过滤器为真的元素的新选择。例如,要筛选表格行以仅包含偶数行:

¥Source · Filters the selection, returning a new selection that contains only the elements for which the specified filter is true. For example, to filter a selection of table rows to contain only even rows:

js
const even = d3.selectAll("tr").filter(":nth-child(even)");

这大致相当于直接使用 d3.selectAll,尽管索引可能不同:

¥This is approximately equivalent to using d3.selectAll directly, although the indexes may be different:

js
const even = d3.selectAll("tr:nth-child(even)");

过滤器可以指定为选择器字符串或函数。如果过滤器是函数,则按顺序为每个选定元素评估该函数,并传递当前数据 (d)、当前索引 (i) 和当前组(节点),并将其作为当前 DOM 元素 (nodes[i])。使用函数:

¥The filter may be specified either as a selector string or a function. If the filter is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). Using a function:

js
const even = d3.selectAll("tr").filter((d, i) => i & 1);

或者使用 selection.select(避免使用箭头函数,因为需要用到箭头函数来引用当前元素):

¥Or using selection.select (and avoiding an arrow function, since this is needed to refer to the current element):

js
const even = d3.selectAll("tr").select(function(d, i) { return i & 1 ? this : null; });

请注意,:nth-child 伪类是从 1 开始的索引,而不是从 0 开始的索引。此外,上述过滤函数的含义与 :nth-child 并不完全相同;它们依赖于选择索引,而不是 DOM 中前导同级元素的数量。

¥Note that the :nth-child pseudo-class is a one-based index rather than a zero-based index. Also, the above filter functions do not have precisely the same meaning as :nth-child; they rely on the selection index rather than the number of preceding sibling elements in the DOM.

返回的过滤选择保留了此选择的父级,但与 array.filter 一样,它不保留索引,因为某些元素可能会被删除;如果需要,使用 selection.select 保存索引。

¥The returned filtered selection preserves the parents of this selection, but like array.filter, it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed.

selection.selectChild(selector) {#selection_selectChild}

源代码 · 返回一个新的选择集,其中包含当前选择集的每个元素的(第一个)子元素与选择器匹配。

¥Source · Returns a new selection with the (first) child of each element of the current selection matching the selector.

js
d3.selectAll("p").selectChild("b") // the first <b> child of every <p>

如果未指定选择器,则选择第一个子项(如果有)。如果选择器指定为字符串,则选择第一个匹配的子节点(如果有)。如果选择器是一个函数,则按顺序为每个子节点求值,传递子节点 (child)、子节点的索引 (i) 和子节点列表 (children);该方法选择第一个选择器返回真值的子项(如果有)。

¥If no selector is specified, selects the first child (if any). If the selector is specified as a string, selects the first child that matches (if any). If the selector is a function, it is evaluated for each of the children nodes, in order, being passed the child (child), the child’s index (i), and the list of children (children); the method selects the first child for which the selector return truthy, if any.

CAUTION

selection.selectChild 将父元素的数据传播给选定的子元素。

¥selection.selectChild propagates the parent’s data to the selected child.

selection.selectChildren(selector) {#selection_selectChildren}

源代码 · 返回一个新的选择集,其中包含当前选择集中与选择器匹配的每个元素的子元素。如果未指定选择器,则选择所有子项。如果选择器指定为字符串,则选择匹配的子节点(如果有)。如果选择器是一个函数,则按顺序为每个子节点求值,传递子节点 (child)、子节点的索引 (i) 和子节点列表 (children);该方法选择所有选择器返回真值的子项。

¥Source · Returns a new selection with the children of each element of the current selection matching the selector. If no selector is specified, selects all the children. If the selector is specified as a string, selects the children that match (if any). If the selector is a function, it is evaluated for each of the children nodes, in order, being passed the child (child), the child’s index (i), and the list of children (children); the method selects all children for which the selector return truthy.

selection.selection() {#selection_selection}

源代码 · 返回选择(与 transition.selection 对称)。

¥Source · Returns the selection (for symmetry with transition.selection).

matcher(selector)

源代码 · 给定指定的选择器,返回一个函数,如果 this 元素 matches 符合指定的选择器,则该函数返回 true。此方法由 selection.filter 内部使用。例如,如下:

¥Source · Given the specified selector, returns a function which returns true if this element matches the specified selector. This method is used internally by selection.filter. For example, this:

js
const div = selection.filter("div");

等同于:

¥Is equivalent to:

js
const div = selection.filter(d3.matcher("div"));

(尽管 D3 不是兼容层,但由于 element.matches 的最新标准化,此实现确实支持带供应商前缀的实现。)

¥(Although D3 is not a compatibility layer, this implementation does support vendor-prefixed implementations due to the recent standardization of element.matches.)

selector(selector)

源代码 · 给定指定的选择器,返回一个函数,该函数返回与指定选择器匹配的 this 元素的第一个后代。此方法由 selection.select 内部使用。例如,如下:

¥Source · Given the specified selector, returns a function which returns the first descendant of this element that matches the specified selector. This method is used internally by selection.select. For example, this:

js
const div = selection.select("div");

等同于:

¥Is equivalent to:

js
const div = selection.select(d3.selector("div"));

selectorAll(selector)

源代码 · 给定指定的选择器,返回一个函数,该函数返回与指定选择器匹配的 this 元素的所有后代。此方法由 selection.selectAll 内部使用。例如,如下:

¥Source · Given the specified selector, returns a function which returns all descendants of this element that match the specified selector. This method is used internally by selection.selectAll. For example, this:

js
const div = selection.selectAll("div");

等同于:

¥Is equivalent to:

js
const div = selection.selectAll(d3.selectorAll("div"));

window(node)

源代码 · 返回指定节点的所属窗口。如果 node 是一个节点,则返回其所属文档的默认视图;如果节点是文档,则返回其默认视图;否则返回节点。

¥Source · Returns the owner window for the specified node. If node is a node, returns the owner document’s default view; if node is a document, returns its default view; otherwise returns the node.

style(node, name)

源代码 · 返回指定节点的指定名称的样式属性值。如果节点具有指定名称的内联样式,则返回其值;否则,返回 计算属性值。另请参阅 selection.style

¥Source · Returns the value of the style property with the specified name for the specified node. If the node has an inline style with the specified name, its value is returned; otherwise, the computed property value is returned. See also selection.style.