weisen Sie eine neue id-Attribut auf jedes element erstellt

Wie ordne ich das id-Attribut zu jedem append Kreis, so dass ich später nutzen kann, die Kreise, basierend auf dessen id. Für jetzt bin ich in der Lage zu Klonen den Kreis ziehen mit id.

Demo: https://jsbin.com/zuxetokigi/1/edit?html,Ausgabe

Code:

 <!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>
  • Versuchen Sie, die "allgemein" - update-Muster und array von Objekten zu mantain eine Liste von Objekten. Diese Objekte können, wie Sie wollen, die Zuordnung erfolgt über Rückrufe in der attr-Funktion. Viel Glück!
InformationsquelleAutor kittu | 2015-07-13
Schreibe einen Kommentar