d3.js中的selection.merge()函數用於將兩個給定的選擇合並為一個,並在合並後返回新選擇。返回的選擇具有與此選擇相同的組數和相同的父代。
用法:
selection.merge(other);
參數:該函數接受單個參數,其他描述選擇將被合並。
返回值:該函數返回一個選擇。
範例1:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" path1tent="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>
// Filtering odd children
const odd = d3.selectAll("h3")
.select(function (d, i) {
return i & 1 ? this:null;
});
// Filtering even children
const even = d3.selectAll("h3")
.select(function (d, i) {
return i & 1 ? null:this;
});
// Merging both selections
const merged = odd.merge(even).nodes();
// Printing text content
console.log(
"Collection after merging odd and even is:")
merged.forEach((e) => {
console.log(e.textContent);
});
</script>
</body>
</html>
輸出:
範例2:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" path1tent="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>
<h5>1. This is odd</h5>
<h5>2. This is even</h5>
<h5>3. This is odd</h5>
<h5>4. This is even</h5>
<h5>5. This is odd</h5>
</div>
<script>
// Filtering odd children
var even = d3.selectAll("h5")
.select(function (d, i) {
return i & 1 ? this:null
});
// Filtering even children
var odd = d3.selectAll("h5")
.select(function (d, i) {
return i & 1 ? null:this
});
// Merging both selections
const merged = odd.merge(even).nodes();
even = even.nodes();
odd = odd.nodes();
console.log("Odd selection:")
odd.forEach((e) => {
console.log(e.textContent);
});
console.log("Even selection:")
even.forEach((e) => {
console.log(e.textContent);
});
// Printing text content
console.log(
"Collection after merging odd and even is:")
merged.forEach((e) => {
console.log(e.textContent);
});
</script>
</body>
</html>
輸出:
相關用法
- p5.js pan()用法及代碼示例
- PHP Ds\Map get()用法及代碼示例
- PHP Ds\Set xor()用法及代碼示例
- PHP next()用法及代碼示例
- PHP Ds\Map put()用法及代碼示例
- PHP Ds\Map xor()用法及代碼示例
- d3.js zip()用法及代碼示例
- d3.js dsv()用法及代碼示例
- d3.js tsv()用法及代碼示例
- PHP chr()用法及代碼示例
- PHP pi( )用法及代碼示例
- d3.js d3.hcl()用法及代碼示例
- d3.js d3.min()用法及代碼示例
注:本文由純淨天空篩選整理自tarun007大神的英文原創作品 D3.js selection.merge() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。