使用javascript获取点击的svg路径的ID

时间:2016-10-11 21:28:50

标签: javascript xml svg

我在马萨诸塞州有一个县的SVG地图。 svg文件包含概述每个县的路径,每个路径的县名称为id。我需要在点击时抓住该县的id,以便将其设置为变量。

编辑: SVG是一个外部文件(它是一个包含大量路径坐标的地图;将整个内容直接复制/粘贴到HTML中似乎很麻烦,所以它是从外部文件加载)。以下是svg文件的示例:

<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/css" href="co25_d00.css"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000303 Stylable//EN"
    "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">

<svg id="MACounties"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   version="1.0" width="100%" height="100%" preserveAspectRatio="xMidYMax" viewBox="12.711167 456.567074 29.566845 18.433033">
<title>Libre Map Project</title>
<g transform="scale(1.0,-1.0) translate(0,-931.567181)">
<g id="Unknown_Area_Type_co25_d00_e00" style="fill:'currentColor';pointer-events:visible;stroke:rgb(1,0,0);stroke-width:0.01;stroke-linecap:round">
    <path id="Essex" d="M34.363079 474.99995L34.363179 474.99967 34.363179 474.99967 34.462128 474.99704 34.596972 474.95046...>

编辑2:这是加载图片的HTML文件。

<html>
<head>
    <title>Untitled</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="co25_d00.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){

              var container = $("#map");
              var svgUrl    = "co25_d00.svg";
              var xmlDoc;

              $.get(svgUrl)
                .then(injectSvg);

              function injectSvg(xmlDoc) {
                var svg = $(xmlDoc).find("svg");
                container.append(svg);
              };

              $(document).ready(function() {
                $('path').onclick = function() {
                    alert($(this).attr('id'));
                };
              });
            });
    </script>
</head>
<body>
    <div id="map"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

您的事件绑定需要在回调中。像

function mockPromise(value) {
  return new Promise(resolve => {
    console.log("I'm not running before I'm queued ...");
    setTimeout(() => {
      resolve(value);
    }, 1000);
  });
}

mockPromise("1st promise").then(x => {
  console.log(x);
  return mockPromise("2nd promise");
}).then(x => {
  console.log(x);
  return mockPromise("3nd promise");
}).then(x => {
  console.log(x);
});