无法在SVG路径元素上执行单击事件

Cec*_*uez 2 javascript jquery svg

我有一个脚本,可以生成带有颜色的地图.当我点击其中一个状态时,我正试图让事件发生 - 这是使用jvectormap.

但是,由于某种原因它不起作用.我在其他元素上尝试,点击事件工作正常.如何使用click事件处理路径元素?

$(function() {
    var generateColors = function() {
      var colors = {},
          key; 
      for (key in map.regions) {
          values.green.forEach(function(item, i) {
             colors[item] = "#2eb02e";
          });
          values.red.forEach(function(item, i) {
             colors[item] = "#ba0707";
          });
          values.yellow.forEach(function(item, i) {
             colors[item] = "#d2d207";
          });
       }
      return colors;
     },
     map = new jvm.Map({
             map: 'us_lcc_en',
             container: $('#map'),
             series: {
                   regions: [{
                      attribute: 'fill'
                   }]
               }
            });
    map.series.regions[0].setValues(generateColors());
});
Run Code Online (Sandbox Code Playgroud)

和:

$("path").click(function() {
     console.log("blah blah blah");
});
Run Code Online (Sandbox Code Playgroud)

优选地,解决方案将使用jQuery.

Gur*_*Rao 8

这可能是因为当您导入它时,页面上没有加载svg标记,因此它无法将事件附加到路径元素.

您需要做的是将一个load事件附加到对象上,一旦加载,它将在点击事件时附加.

你可以这样做

$(document).on('click','path',function(){
        alert('You clicked me');
        //Do the stuff
});
Run Code Online (Sandbox Code Playgroud)

要么

<script>
        var a = document.getElementById("somesvg");
        //it's important to add an load event listener to the object, as it will load the svg doc asynchronously
        a.addEventListener("load",function(){
            var svgDoc = a.contentDocument; //get the inner DOM of some.svg
            var delta = svgDoc.getElementById("delta"); //get the inner element by id
            delta.addEventListener("mousedown",function(){alert('hello world!')},false);    //add behaviour
        },false);
</script>
Run Code Online (Sandbox Code Playgroud)

注 -请注意,此技术的限制是它受同源策略的限制,因此some.svg必须与html文件托管在同一域中,否则对象的内部DOM将无法访问.