有没有办法只检索添加到特定点的子项。例如,我创建了
rect and circle
并在添加 fnTwo
之前执行 path
,希望它只返回 rect and circle
。但它会返回所有的孩子;例如rect, circle +path
;即使之后添加了路径。有没有办法让我执行 fnTwo
来获取到该时间点添加的孩子。
const svg = document.querySelector('svg');
const svgns = "http://www.w3.org/2000/svg"
const element = ['rect', 'circle'];
//fn for append
const fnOne = (element) => {
const child = document.createElementNS(svgns, element);
svg.append(child);
}
//append all elements
for (const elements of element) {
const element = elements;
fnOne(element)
};
// get all the children elements **up to this point in time**
const fnTwo = (element) => {
const children = element.children;
//do something with the children
console.log(children); //brings all children added before + after
}
const children = fnTwo(svg);
//add a path to test if it is retrieved through fnTwo
const childThree = document.createElementNS(svgns, 'path');
svg.append(childThree);
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<svg>
</svg>
</body>
</html>
您遇到的问题是因为您返回了原始的子“数组”,您需要做的是返回一个副本:
const svg = document.querySelector('svg');
const svgns = "http://www.w3.org/2000/svg"
const element = ['rect', 'circle'];
//fn for append
const fnOne = (element) => {
const child = document.createElementNS(svgns, element);
svg.append(child);
}
//append all elements
for (const elements of element) {
const element = elements;
fnOne(element)
};
// get all the children elements **up to this point in time**
const fnTwo = (element) => {
const children = [...element.children]; //shallow copy of the array
//do something with the children
console.log(children); //brings all children added before + after
}
const children = fnTwo(svg);
//add a path to test if it is retrieved through fnTwo
const childThree = document.createElementNS(svgns, 'path');
svg.append(childThree);
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<svg>
</svg>
</body>
</html>