You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌入外部SVG文件元素时出现Uncaught TypeError错误的求助

嵌入外部SVG文件元素时出现Uncaught TypeError错误的求助

我知道这个问题不算新鲜,也找了一些解决思路,但就是没法搞定。先贴一下我的简单代码:

<!doctype html>
<html lang="de">
    <head>
        <title>SVG Test</title>
    </head>
    <body>
        <h1>Select a circle</h1>
        <object id="svg-object" data="circle.svg" width="200" height="200"></object>

        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400">
            <circle id="circle" class="svg-element" cx="50" cy="50" r="40" />
        </svg>

        <script>
            // do this if selected
            function handleClick(elementId) {
                alert('"' + elementId + '" selected');
            }

            // event listener
            document.getElementById("circle").addEventListener("click", function () {
                handleClick("circle");
            });

            // event listener
            document.getElementById("circle_in_svg").addEventListener("click", function () {
                handleClick("circle_in_svg");
            });
        </script>
    </body>
</html>

页面上会显示两个圆形,外部的circle.svg文件内容和<object>标签下方的三行SVG代码完全一致,只是把id从circle改成了circle_in_svg。

目前的情况是:

  • 脚本代码放在了<object>标签之后,按道理circle_in_svg这个元素应该能被获取到才对
  • 两个圆形显示正常,顺序是先显示外部文件里的圆,再显示内联的圆
  • 试过加defer或async属性,都没用。而且我觉得不加这两个属性的话,浏览器应该是加载完文件再继续执行脚本,所以元素ID应该是可用的

但页面加载后,用F12在火狐里看到报错:Uncaught TypeError: document.getElementById(...) is null,结果当然没法正常工作...

有没有大佬能帮忙解决一下?

备注:内容来源于stack exchange,提问作者imarti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 14:29:33