简体   繁体   中英

Add external handler for onlick event to SVG element

I trying to add JS handler to some my SVG's children. I using following code inside SVG:

  <script type="text/javascript" id="script3079">
    addClickEvents();

    function addClickEvents() {
        var keys = document.getElementsByTagName('path');
        for (var i=0; i &lt; keys.length; i++){
            keys[i].addEventListener('click', keyClicked);
        }
    }

    function keyClicked(e) {
        var node = e.target;
        alert(node.id);
    }
  </script>

And it is working ok. But now I want to call function from EXTERNAL javascript file:

//myfile.js
function keyClickedExternal(e) {
  alert('keyClickedExternal');
}

Of course it is attached to my HTML via script tag.

I tried following bindings:

keys[i].addEventListener('click', keyClickedExternal); //keyClickedExternal undefined
keys[i].addEventListener('click', parent.keyClickedExternal); //keyClickedExternal undefined
keys[i].addEventListener('click', top.keyClickedExternal); //keyClickedExternal undefined
keys[i].addEventListener('click', parent.keyClickedExternal); //keyClickedExternal undefined

I checked DOM:

parent.window.document //access violation
window.document //refers to SVG document
document //the same as previous

Finally, I do not understand how to bind external handler to SVG child.

As @Robert Longson said problem was related to Chrome's security - it is treating other local file as different domain. Use the webserver, Luk.

You should add document.domain = 'Your_domain_name'; at the beginning line of each JavaScript files, I also recommend reading about crossdomain.xml file about running scripts from different domain names (eg: statics.yourdomain.com including static css, js, img files)

PS: Sorry for late reply, I was looking for something else and saw that your question remained non-replied

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