为创建的每个元素分配新的id属性

kit*_*ttu 2 d3.js

如何将id属性分配给圆的每个追加,以便以后可以根据其id使用圆。现在,我能够在拖动时克隆出没有任何id的圆。

演示:https : //jsbin.com/zuxetokigi/1/edit?html,输出

码:

 <!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>
Run Code Online (Sandbox Code Playgroud)

Del*_*lan 6

我不确定为什么要这么做,但是如果您想给每个圆圈一个唯一的ID,则可以使用一个函数为每个圆圈生成一个GUID / UUID(“全局唯一标识符”)。

您可以将Salvik Meltser的GUID / UUID函数中的以下函数添加到代码中(该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();
}
Run Code Online (Sandbox Code Playgroud)

然后,在您添加新圆圈的位置,只需用于.attr("id", guid())生成该圆圈的新ID。

var circle2 = d3.select("svg").append("circle")
    .attr("id", guid())  
    .classed("drg", true)
    ...
Run Code Online (Sandbox Code Playgroud)