在元素SVG中使用JavaScript或jQuery单击事件?

我正在使用SVG创建一个Web应用程序,但我遇到了一个问题:

我需要使用jQuery在包含SVG的每个元素上单击一个事件.当我尝试执行事件时出现问题;就好像元素只是由点构造而且事件非常不稳定.我的代码如下……

<figure id="'+id+'" cod="'+cod+'" class="contentOneDent">
<div class="textDent headDent">'+id+'</div>
    <svg class="figureDent" viewBox="0 0 6598 10423">
     <g id="Capa_x0020_1">
      <path     cod="'+ZONE_C_VESTIBULAR_S+'" class="faceDent dent1 CervicalVestibularS" d="M1113 2675c-314,-318 -631,-637 -958,-958 1118,-2319 5691,-2126 6257,-42l-908 1018c-580,-562 -1354,-906 -2205,-906 -841,0 -1608,336 -2186,888z"/>
      <ellipse  cod="'+ZONE_OCLUSAL+'" class="faceDent dent1 Oclusal" cx="3299" cy="5214" rx="1370" ry="1443"/>
      <path     cod="'+ZONE_C_VESTIBULAR_I+'" class="faceDent dent1 CervicalVestibularI" d="M1111 7751c-314,317 -630,634 -956,955 1118,2319 5691,2126 6257,42l-906 -1016c-580,564 -1355,909 -2207,909 -843,0 -1610,-337 -2188,-890z"/>
      <path     cod="'+ZONE_PALATINA+'" class="faceDent dent1 Palatina" d="M2487 6371c-472,463 -922,921 -1376,1380 578,553 1345,890 2188,890 852,0 1627,-345 2207,-909l-1293 -1450c-465,404 -1156,510 -1726,89z"/>
      <path     cod="'+ZONE_MESIAL+'" class="faceDent dent1 Mesial" d="M2484 6374c-471,462 -920,919 -1373,1377 -655,-627 -1066,-1532 -1066,-2537 0,-1008 413,-1914 1071,-2541l-3 2c454,457 903,914 1374,1377l2 -2c-339,263 -560,686 -560,1164 0,475 218,897 555,1160z"/>
      <path     cod="'+ZONE_DISTAL+'" class="faceDent dent1 Distal" d="M5504 2693c645,626 1049,1524 1049,2521 0,995 -403,1892 -1047,2518l-1290 -1447c278,-264 453,-646 453,-1071 0,-427 -176,-810 -455,-1074l1290 -1447z"/>
      <path     cod="'+ZONE_VESTIBULAR+'" class="faceDent dent1 Vestibular" d="M3299 1787c851,0 1625,344 2205,906l-1291 1448c-465,-405 -1156,-510 -1726,-89 -471,-463 -920,-920 -1374,-1377 578,-552 1345,-888 2186,-888z"/>
     </g>
    </svg>
<figcaption class="textDent footDent"></figcaption>
</figure>

当我使用类faceDent单击元素时,我需要执行一个函数.

有谁知道我如何正确实施该事件?

最佳答案 对于动态生成的html,您可以使用.on()来触发事件.假设您要将动态生成的html添加到ID为“dynamicDiv”的div中,那么脚本就像:

<script>
    $(document).ready(function(){
        $("#dynamicDiv").on("click", ".faceDent", function(){
            // your code goes here
            // $(".faceDent ").attr("fill", "red");
        });
    });
</script>

附:如果您在角度js中动态生成html,那么您应该考虑专门编译它.

$compile的文档:https://docs.angularjs.org/api/ng/service/ $compile

点赞