简体   繁体   中英

Embedded SVG paths onclick get id

I'm trying to store the id of a clicked path of a SVG file inserted as object into the HTML document but I can't get it and still don't understand the problem.

I would like to end up with a clickable map divided in areas that will display some data (in the div#data) depending on the clicked zone. The data could be retrieved from a xml file.

Maybe there is a simpler approach to get this done. Please, could I get some help?

Thanks

PARTIAL SVG CODE:

<defs>...
    <style>
        ...
    </style>
</defs>
<title>title here</title>
<g id="group1">
    <path id="zone1" onClick="selected(this.id)"  d="M482.56,0l-2,7a26.85,26.85,0,0,1-.79,4.26,20.67,20.67,0,0,0-.21,3.7,16.67,16.67,0,0,1-3.38,7.38c-1,1.48-.89,3.27-2.54,4.18-.9.5-.89,2.27-1.74,3.23-2.6,2.91-4.88,3.6-8.68,3-2.41-.39-4,2...

HTML CODE:

<article id="map">
    <object id="svg" type="image/svg+xml" data="images/mapa.svg">Your browser does not support SVG</object>
    <div id="result">
        <h3>header</h3>
        <div id="data" class="data"></div>
    </div>
</article>

JS CODE :

function selected(clicked_id){
     alert(clicked_id);
};

Why this script is not showing the id?

I tried your logic and it worked for me. However, one difference is that the snippet contains the SVG DOM entirely. I don't know if Stackoverflow supports uploading separate files to be used as external SVG.

In my snippet I used jQuery to attach click events to SVG paths.

 $(".heart").click(function(){ var color = $(this).attr("fill"); console.log(color,"clicked"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <h1>Click a heart!</h1> <svg width="200" height="100" style="background-color: #bada55" > <g transform="scale(1.2)"> <path class="heart" d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" fill="red"></path> </g> <g transform="scale(0.8) translate(140,40)"> <path class="heart" d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" fill="black"></path> </g> </svg> 

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