开发者问题收集

SVG 元素 onclick 给出 ReferenceError:函数未定义

2015-02-04
2820
svg

我尝试向 svg 元素添加 onclick 事件。

因此,我向下面的特定元素添加了一个 onclick 属性。但是它似乎不起作用。

我收到以下错误:“Uncaught ReferenceError:clickCounty 未定义”

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script>
                function clickCounty(e)
                {
                    console.log("clickCounty");
                }
            });
        </script>
    </head>
    <body>
        <div id="canvas">
            <object data="custom.svg" type="image/svg+xml">
        </div>
    </body>
</html>

custom.svg

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect onclick="clickCounty('test')" x="10" y="10" height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
</svg>
3个回答

您有两个问题

a) 您的脚本语法错误,在脚本末尾有一行多余的 });

   <script>
            function clickCounty(e)
            {
                console.log("clickCounty");
            }
    </script>

b) 您需要 window.top 或 window.parent 才能从 svg 文档访问 html 文档中定义的方法,例如

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect onclick="window.parent.clickCounty('test')" x="10" y="10" height="100" width="100" style="stroke:#006600; fill: #00cc00"/>
</svg>
Robert Longson
2015-02-04

通过在标记中逐字包含 SVG 内容/元素解决了这个问题。

当通过 <object> 标签嵌入它时,它给出了引用错误。不知道为什么会发生这种情况....

Chris Stryczynski
2015-02-04

我用这个,对我有用

 <svg ...
       (click)="testClick(point)"
 >
   ....
 </svg>
Andran
2020-09-01