SVG 在 JS 中单击事件的对象问题

SVG in object problems with click event inside JS

我在 HTML 文档的对象元素中有一个 svg 图像。

<object id="svg1" data="nejc/bg.svg" type="image/svg+xml">
Your browser doesn't support SVG
</object>

我有 javascript 代码。在它里面我添加了点击事件,当 svg 完成加载时执行。代码在我添加到元素组上的 .svg 文件中查找 id。一切正常。但是我时不时遇到问题,当我加载页面时,无法单击 svg 元素,但如果我刷新它,则单击工作正常。

$( document ).ready(function() {

    //button where are you
    var a = document.getElementById("svg1");

    //it's important to add an load event listener to the object, as it will load the svg doc asynchronously
    a.addEventListener("load",function(){
        var svgDoc = a.contentDocument; //get the inner DOM of svg
        var delta = svgDoc.getElementById("right"); //get the inner element by id
        delta.addEventListener("click",function(){
                this.style.fill = '#DC7827';
                 setTimeout("document.location.href = '_mobile_whereareyou.php';",200);

        },false);    //add behaviour
    },false);

    //button place ID
    var b = document.getElementById("svg1");

    //it's important to add an load event listener to the object, as it will load the svg doc asynchronously
    b.addEventListener("load",function(){
        var svgDocB = b.contentDocument; //get the inner DOM of svg
        var beta = svgDocB.getElementById("left"); //get the inner element by id
        beta.addEventListener("click",function(){
                this.style.fill = '#DC7827';
                setTimeout("document.location.href = '_mobile_placeID.php';",200);

        },false);    //add behaviour
    },false);

  });

我猜测当无法单击 svg 元素时,svg 图像未正确加载。有什么方法可以确保 svg 元素已加载并且点击正常工作?

我想我找到了解决方案。我的想法是正确的,当点击不起作用时 svg 没有正确加载。所以我将所有代码包装在下面的块中。

$('#svg1').load('nejc/bg.svg', null, function() { 
//here is now my code given in question
});

此函数加载 svg 并在完成时执行函数中的代码。