简体   繁体   中英

Inject SVG element and access it using jquery

I am creating svg element (a point) dynamically inside of graphic-content class and the trying to access the point element using jquery but its not working. Any sol.?

 /* code for creating svg element */
 $(document).ready(function(){
    var x = 0,
    $y1 = 0;
    $con = $(".graphic-content");

    var $svg = $(svg("svg")).attr({
     "width": "946", "height": "280"
     }).appendTo($con);

   /* create a point */
      $(function() {
         $(svg("circle")).attr({
         "cx": x, "cy": $y1,"r":"3","class":"point"
          }).appendTo($svg);
  });
   /* hover effect*/
 $("circle").hover(function(){
   $(this).css("cursor", "pointer");
   alert("Hello!");
 });
});
function svg(elem) {
       return document.createElementNS("http://www.w3.org/2000/svg", elem);
    }

x and $y1 do not appear to be defined? Try using mouseenter , mouseleave events attached to svg , event delegation. Removing alert() call; setting cursor:point using .toggleClass()

 /* code for creating svg element */ $(document).ready(function() { var x = 0, $y1 = 0; $con = $(".graphic-content"); var $svg = $(svg("svg")).attr({ "width": "946", "height": "280" }).appendTo($con); /* create a point */ $(function() { $(svg("circle")).attr({ "cx": x, "cy": $y1, "r": "3", "class": "point" }).appendTo($svg); }); /* hover effect*/ $("svg").on("mouseenter", "circle", function(e) { console.log(e); $("body").toggleClass("hovered"); // alert("Hello!"); }).on("mouseleave", "circle", function(e) { console.log(e); $("body").toggleClass("hovered") }) }); function svg(elem) { return document.createElementNS("http://www.w3.org/2000/svg", elem); }
 .hovered { cursor: pointer; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div class="graphic-content"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM