SVG element onclick gives ReferenceError: function is not defined

SVG element onclick gives ReferenceError: function is not defined

我正在尝试将 onclick 事件添加到 svg 元素。

所以我在下面的特定元素中添加了一个 onclick 属性。但是它似乎没有用。

我得到以下错误:"Uncaught ReferenceError: clickCounty is not defined"

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>

通过在标记中直接包含 SVG 内容/元素来解决此问题。

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

你有两个问题

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>

我用这个,为我工作

 <svg ...
       (click)="testClick(point)"
 >
   ....
 </svg>