2015-07-13 126 views
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> 
+0

尝试使用[一般更新模式](http://bl.ocks.org/mbostock/3808218)和对象数组来维护对象列表。这些对象可以像你想的那样,映射是通过attr函数中的回调完成的。祝你好运! –

回答

4

我不知道是什么原因,你会想这样做,但如果你想给每一个圆圈一个唯一的ID,你可以使用函数为每个圆圈生成一个GUID/UUID('全局唯一标识符')。

您可以添加从Salvik Meltser's GUID/UUID function下面的函数代码(之前任何地方drag功能):

function guid() { 
    function _p8(s) { 
     var p = (Math.random().toString(16)+"000000000").substr(2,8); 
     return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ; 
    } 
    return _p8() + _p8(true) + _p8(true) + _p8(); 
} 

然后,在这里您将追加新的循环,只是用.attr("id", guid())产生了一个新的ID圈。

var circle2 = d3.select("svg").append("circle") 
    .attr("id", guid()) 
    .classed("drg", true) 
    ... 
相关问题