d3.js中的d3.selection.filter()函數用於過濾給定的選擇並返回其過濾器為true的新選擇。要使用的過濾器可以是字符串或函數。
用法:
selection.filter(filter);
參數:該函數接受上麵提到並在下麵描述的一個參數:
- filter:它是一個字符串或一個函數,用於過濾選擇。使用函數時,過濾器將應用於每個選定的元素。
返回值:此函數返回新選擇。
範例1:本示例選擇指定元素的所有奇數子代。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width,initial-scale=1.0">
<script src=
"https://d3js.org/d3.v4.min.js">
</script>
<script src=
"https://d3js.org/d3-selection.v1.min.js">
</script>
</head>
<body>
<div>
<b>1. This text is in bold</b>
<b>2. This text is also in bold</b>
<b>3. Geeks for geeks</b>
<b>4. Geeks for geeks</b>
<b>5. Geeks for geeks</b>
</div>
<script>
let selection = d3.selectAll("b")
.filter(":nth-child(odd)")
.nodes();
selection.forEach((e) => {
console.log(e.textContent)
})
</script>
</body>
</html>
輸出:
範例2:本示例選擇指定元素的所有偶數子代。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width,initial-scale=1.0">
<script src=
"https://d3js.org/d3.v4.min.js">
</script>
<script src=
"https://d3js.org/d3-selection.v1.min.js">
</script>
</head>
<body>
<div>
<b>1. This text is in bold</b>
<b>2. This text is also in bold</b>
<b>3. Geeks</b>
<b>4. Geeks</b>
<b>5. Geeks for geeks</b>
</div>
<script>
let selection = d3.selectAll("b")
.filter(":nth-child(even)")
.nodes();
selection.forEach((e) => {
console.log(e.textContent)
})
</script>
</body>
</html>
輸出:
範例3:本示例使用selection.selectAll作為過濾器。
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<script src=
"https://d3js.org/d3.v4.min.js">
</script>
<script src=
"https://d3js.org/d3-selection.v1.min.js">
</script>
</head>
<body>
<div>
<h3>1. This text is in bold</h3>
<h3>2. This text is also in bold</h3>
<h3>3. Geeks</h3>
<h3>4. Geeks</h3>
<h3>5. Geeks for geeks</h3>
</div>
<script>
// Using selection.selectAll with filter
let selection = d3.selectAll("div")
.selectAll("h3")
.filter(":nth-child(even)")
.nodes();
selection.forEach((e) => {
console.log(e.textContent)
})
</script>
</body>
</html>
輸出:
相關用法
- PHP imagecreatetruecolor()用法及代碼示例
- p5.js year()用法及代碼示例
- d3.js d3.utcTuesdays()用法及代碼示例
- PHP ImagickDraw getTextAlignment()用法及代碼示例
- PHP Ds\Sequence last()用法及代碼示例
- PHP array_udiff_uassoc()用法及代碼示例
- PHP geoip_continent_code_by_name()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- PHP GmagickPixel setcolor()用法及代碼示例
- PHP opendir()用法及代碼示例
- PHP cal_to_jd()用法及代碼示例
- d3.js d3.bisectLeft()用法及代碼示例
- PHP stream_get_transports()用法及代碼示例
- PHP Ds\Deque pop()用法及代碼示例
注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 D3.js selection.filter() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。