【问题标题】:How to call functions defined in parent document from an svg referenced by an <object> element?如何从 <object> 元素引用的 svg 调用父文档中定义的函数?
【发布时间】:2014-08-18 07:31:38
【问题描述】:

我曾经将 svg 文件嵌入到我的网页中:

    <object id="svgmap" width="100%" height="100%" data="<%=path %>/svg/map.svg" type="image/svg+xml" style="">
    </object>

然后我使用一个名为“support.js”的外部javascript文件在这个svg文件中添加了一些图像标签:

    var marker = document.createElementNS(xmlns, 'image');
    marker.setAttributeNS(null, 'id', "img_0123");
    marker.setAttributeNS('http://www.w3.org/1999/xlink', 'href', iconurl);
    marker.setAttributeNS(null, 'x', posX);
    marker.setAttributeNS(null, 'y', posY);
    marker.setAttributeNS(null, 'visibility', 'visible');
    marker.setAttribute("onclick", "onsel('0123')");

这个“onsel”函数也在 support.js 中定义,所以当我点击图片时,它会变成另一个图片。现在,当我在浏览器(Opera、Mozilla 和 Chrome)中查看此页面时,当我单击该图像时它并没有切换到另一个图像,并且在开发人员工具的控制台中,它说“referenceerror: onsel is not defined svgmap:1 ”。

这是否意味着 svg 文件不能使用在其他 javascript 文件中定义的函数?该怎么做?

【问题讨论】:

    标签: javascript html svg


    【解决方案1】:

    我已将您的问题解释为“如何从 元素引用的 svg 调用父 html 文档范围内定义的函数?”。从你的“onsel”函数定义的问题中有点不清楚,但我猜它是在 html 文档内的脚本中。

    这是一个 example 如何从 svg 内部调用到父级。父级中的函数打印单击了哪个元素以及引用了哪个元素。

    从 svg 到父文档:

        window.parent.yourFunctionInParentDocument();
    

    【讨论】:

    • 正是我一直在寻找的!非常感谢!
    猜你喜欢
    • 2012-05-16
    • 2019-06-05
    • 2021-02-03
    • 2019-02-03
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多