如何在网页中的svg路径中添加id?

时间:2018-03-20 01:00:11

标签: javascript svg

这是我的网页:

<html>
    <head>
        <title>Bin Labeler</title>
    </head>
    <body>
        <embed class="emb" src="racks.svg" style="position: relative;
            width:100%;
            height:100%"/>
            <script>//<![CDATA[
// wait until all the resources are loaded
window.addEventListener("load", findSVGElements, false);

// fetches the document for the given embedding_element
function getSubDocument(embedding_element)
{
    if (embedding_element.contentDocument) 
    {
        return embedding_element.contentDocument;
    } 
    else 
    {
        var subdoc = null;
        try {
            subdoc = embedding_element.getSVGDocument();
        } catch(e) {}
        return subdoc;
    }
}
function findSVGElements()
{
    var elm = document.querySelector('.emb');
    var subdoc = getSubDocument(elm);
    if (subdoc)
            var paths = subdoc.querySelectorAll("path");
                paths.forEach(function(path){
                  path.addEventListener('click',function(e){
                var bin_id = prompt("What ID belongs to this rack?","Enter here...");
                e.target.id=bin_id;
                path.setAttribute('fill','green');
                console.log(e.target);
                    })
                });
}

//]]>

            </script>
    </body>
</html>

正如您所看到的,它将svg xml加载到我的findSVGElements函数中,然后为每个函数添加一个事件监听器,警报会显示要求id。然后我设置e.target.id希望将id元素添加到svg。然后当我做&#34; View Frame source&#34;它给出了svg及其所有路径,我希望用户键入警告框的bin_id成为该路径元素的id属性。但是,当我查看帧源时,它似乎没有这样做,我只是查看加载到页面的原始svg。

我该怎么做?

0 个答案:

没有答案