leu*_*shz 5 javascript svg d3.js
在d3程序中,我需要获取一个节点(带有d3.selection)然后我想插入相同的svg.
我知道有一些函数,如append和insert,但这些函数适用于新元素.
var node = d3.select("rect#someId"); //node with some attributes and listeners
Run Code Online (Sandbox Code Playgroud)
现在我的var节点获得了以下属性:{_ groups,_parents}
var anotherNode = d3.select("anotherNode").insert(node); //It work but it would be great a similar function or a workaround
Run Code Online (Sandbox Code Playgroud)
注意.我需要保留节点的监听器
使用此功能克隆您的选择:
var copy = d3.select("#group").clone(true).attr("transform", "translate(120,100)");Run Code Online (Sandbox Code Playgroud)
然后,您可以使用selection.clone(通过ID)或selection.clone(按类)调用它.
下面是一个示例,其中克隆了ID为"group"的组(一个矩形和一个圆圈)(翻译只是为了更好地查看克隆):
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="200" height="200">
<g id="group">
<rect x="10" y="10" width="50" height="20" fill="teal"></rect>
<circle cx="35" cy="40" r="20" fill="red"></circle>
</g>
</svg>Run Code Online (Sandbox Code Playgroud)
function clone(selector) {
var node = d3.select(selector).node();
return d3.select(node.parentNode.insertBefore(node.cloneNode(true), node.nextSibling));
}
Run Code Online (Sandbox Code Playgroud)
PS:这不会克隆听众.此外,这个功能不是我的,它是由博斯托克写的.