控制流程
對於進階使用,選取提供自訂控制流程的方法。
selection.each(function)
原始碼 · 依序呼叫每個選取元素指定的 function,傳入目前的資料 (d)、目前的索引值 (i) 和目前的群組 (nodes),其中 this 為目前的 DOM 元素 (nodes[i])。這個方法可用於呼叫每個選取元素的任意程式碼,且對於建立同時存取父層和子層資料的內容很有用,例如
js
parent.each(function(p, j) {
d3.select(this)
.selectAll(".child")
.text(d => `child ${d.name} of ${p.name}`);
});
請參閱 大小調整的甜甜圈倍數 以取得範例。
selection.call(function, ...arguments)
原始碼 · 僅呼叫指定的 function 一次,傳入此選取和任何選用的 arguments。傳回此選取。這等同於手動呼叫函式,但有助於方法串連。例如,要在可重複使用的函式中設定多種樣式
js
function name(selection, first, last) {
selection
.attr("first-name", first)
.attr("last-name", last);
}
現在說
js
d3.selectAll("div").call(name, "John", "Snow");
這大致等於
js
name(d3.selectAll("div"), "John", "Snow");
唯一的不同是 selection.call 永遠傳回 selection,而不是被呼叫的 function,name
的傳回值。
selection.empty()
原始碼 · 如果這個選取不包含任何(非空值)元素,傳回 true。
js
d3.selectAll("p").empty() // false, here
selection.nodes()
原始碼 · 傳回這個選取中所有(非空值)元素的陣列。
js
d3.selectAll("p").nodes() // [p, p, p, …]
等於
js
Array.from(selection)
selection[Symbol.iterator]()
原始碼 · 傳回選取的(非空值)元素的迭代器。例如,要迭代選取的元素
js
for (const element of selection) {
console.log(element);
}
要將選取扁平化成陣列
js
const elements = [...selection];
selection.node()
原始碼 · 傳回這個選取中的第一個(非空值)元素。如果選取是空的,傳回 null。
selection.size()
原始碼 · 傳回這個選取中(非空值)元素的總數。