小编典典

jQuery的追加不适用于SVG元素?

html

假设这样:

<html>
<head>
 <script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript">
 $(document).ready(function(){
  $("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');
 });
 </script>
</head>
<body>
 <svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px">
 </svg>
</body>

我为什么看不到任何东西?


阅读 917

收藏
2020-05-10

共1个答案

小编典典

当您将标记字符串传递到时$,会使用(或其他适用于特殊情况的容器)容器innerHTML上的浏览器属性将标记字符串解析为HTML
。无法解析SVG或其他非HTML内容,即使可以,也无法分辨出该内容应该在SVG命名空间中。<div>``<tr>``innerHTML``<circle>

innerHTML在SVGElement上不可用-
它仅是HTMLElement的属性。当前没有innerSVG属性或其他方法(*)将内容解析为SVGElement。因此,您应该使用DOM样式的方法。jQuery不能让您轻松访问创建SVG元素所需的命名空间方法。确实jQuery并非完全设计用于SVG,许多操作可能会失败。

HTML5承诺将来会在<svg>没有xmlns纯HTML(text/html)文档的情况下使用。但这只是一个解析器hack(**),SVG内容仍将是SVG命名空间中的SVGElements,而不是HTMLElements,因此innerHTML即使它们
看起来 像HTML文档的一部分,也将无法使用。

但是,对于当今的浏览器,您必须使用 X
HTML(正确用作application/xhtml+xml;保存为.xhtml文件扩展名以进行本地测试)才能使SVG正常工作。(无论如何,这都是有意义的;
SVG是一个基于XML的适当标准。)这意味着您必须对<脚本块中的符号进行转义(或将其包含在CDATA部分中),并包括XHTML xmlns声明。例:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
</head><body>
    <svg id="s" xmlns="http://www.w3.org/2000/svg"/>
    <script type="text/javascript">
        function makeSVG(tag, attrs) {
            var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
            for (var k in attrs)
                el.setAttribute(k, attrs[k]);
            return el;
        }

        var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
        document.getElementById('s').appendChild(circle);
        circle.onmousedown= function() {
            alert('hello');
        };
    </script>
</body></html>

*:是的,有DOM Level 3 LS的parseWithContext,但是浏览器支持非常差。编辑添加:但是,虽然不能将标记注入SVGElement中,但是可以使用来将新的SVGElement注入HTMLElement中innerHTML,然后将其传输到所需的目标。不过,它可能会慢一些:

<script type="text/javascript"><![CDATA[
    function parseSVG(s) {
        var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
        var frag= document.createDocumentFragment();
        while (div.firstChild.firstChild)
            frag.appendChild(div.firstChild.firstChild);
        return frag;
    }

    document.getElementById('s').appendChild(parseSVG(
        '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
    ));
]]></script>

**:我讨厌HTML5的作者似乎害怕XML,并决心将基于XML的功能塞入残酷的HTML中。XHTML在几年前解决了这些问题。

2020-05-10