2
如何为id的每个附加属性分配id属性,以便稍后可以使用基于id的圆圈。现在,我可以通过拖出任何标识来克隆该圈子。为每个创建的元素分配新的id属性
演示:https://jsbin.com/zuxetokigi/1/edit?html,output
代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.js"></script>
<script>
svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
circle1 = svg.append("circle")
.attr("id", "circleToClone")
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 20);
var drag = d3.behavior.drag()
.origin(function()
{
var t = d3.select(this);
return {x: t.attr("cx"), y: t.attr("cy")};
})
.on('dragend', function (d) {
var mouseCoordinates = d3.mouse(this);
if (mouseCoordinates[0] > 120) {
//Append new element
var circle2 = d3.select("svg").append("circle")
.classed("drg", true)
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 20)
.attr("cx", mouseCoordinates[0])
.attr("cy", mouseCoordinates[1])
.style("fill", "green");
}
});
circle1.call(drag);
</script>
</body>
</html>
尝试使用[一般更新模式](http://bl.ocks.org/mbostock/3808218)和对象数组来维护对象列表。这些对象可以像你想的那样,映射是通过attr函数中的回调完成的。祝你好运! –