如何从嵌入式svg中调用父html文档中的函数 [英] How to call a function in the parent html document from an embedded svg

查看:161
本文介绍了如何从嵌入式svg中调用父html文档中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对svg很新,我必须用它执行任务,但我遇到了很多麻烦。

I'm quite new to svg and I have to perform a task with it, but I'm having lots of troubles.

我有一个svg(一个例如地图)由路径定义的区域。

I have an svg (a map for instance) with areas defined by paths.

我的目标是触发onClick svg外部的一个函数来做一些事情(例如,通过ajax检索某些人与所选区域相关的数据,并在html页面的svg外显示。)

My goal is to trigger onClick a function external to the svg to do some stuff (for instance, retrieving by ajax some people data related to the area selected and show them outside the svg in the html page).

我无法做的是触发在svg外定义的函数来自svg中的一个元素。

What I'm not able to do is to trigger a function defined outside the svg from an element in the svg.

如果我添加svg内联,我可以这样做,但我需要使用embed标签使其与Adobe插件一起使用。有什么建议吗?在此先感谢。

I can do this if i add the svg inline, but I need to use the embed tag to make it work with ie Adobe plugin. Any suggestion? Thanks in advance.

推荐答案

参见这个例子

svg中的代码如下所示:

The code inside the svg looks like this:

    document.getElementById("svgroot").addEventListener("click", 
                                                        sendClickToParentDocument,
                                                        false);

    function sendClickToParentDocument(evt)
    {
        // SVGElementInstance objects aren't normal DOM nodes, 
        // so fetch the corresponding 'use' element instead
        var target = evt.target;
        if(target.correspondingUseElement)
            target = target.correspondingUseElement;

        // call a method in the parent document if it exists
        if (window.parent.svgElementClicked)
            window.parent.svgElementClicked(target);
        else
            alert("You clicked '" + target.id + "' which is a " + target.nodeName + " element");
    }

在父文档中,您有一个脚本,其中包含您要调用的函数,例如:

And in the parent document you have a script with a function you want to call, e.g:

function svgElementClicked(theElement)
{
    var s = document.getElementById("status");
    s.textContent = "A <" + theElement.nodeName + 
        "> element with id '" + theElement.id + 
        "' was clicked inside the <" + 
        theElement.ownerDocument.defaultView.frameElement.nodeName.toLowerCase() + 
        "> element.";
}

这篇关于如何从嵌入式svg中调用父html文档中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆