假设:

<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>

为什么我什么都看不到?


当前回答

我建议最好使用ajax并从另一个页面加载svg元素。

$('.container').load(href + ' .svg_element');

其中href是带有svg. xml的页面的位置。通过这种方式,您可以避免替换html内容时可能发生的任何紧张影响。另外,不要忘记在svg加载后打开它:

$('.svg_element').unwrap();

其他回答

一个更简单的方法是将SVG生成为字符串,创建包装器HTML元素,并使用$(“#wrapperElement”). HTML (svgString)将SVG字符串插入到HTML元素中。这在Chrome和Firefox中工作得很好。

我可以看到圈在firefox,做2件事:

1)将文件从html重命名为xhtml

2)更改脚本为

<script type="text/javascript">
$(document).ready(function(){
    var obj = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    obj.setAttributeNS(null, "cx", 100);
    obj.setAttributeNS(null, "cy", 50);
    obj.setAttributeNS(null, "r",  40);
    obj.setAttributeNS(null, "stroke", "black");
    obj.setAttributeNS(null, "stroke-width", 2);
    obj.setAttributeNS(null, "fill", "red");
    $("svg")[0].appendChild(obj);
});
</script>

我为此做了一个小函数。对于jQuery的追加方法,问题是需要为SVG指定命名空间,即“http://www.w3.org/2000/svg”更多

如果我准备它为appendmethod呢?在这种情况下,你只需要提供一些参数:

tagName:它可以是每一个SVG元素,如矩形,圆,文本,g等。

text:如果您正在使用类似text tagname的东西,则需要指定text

和SVG元素的其他已知属性。

因此,我要做的是定义一个名为createSvgElem()的函数,它在内部使用document.createElementNS()。

这里有一个例子:

$("svg").append(
   createSvgElem({tagName: "text", x: 10, y: 10, text: "ABC", style: "fill: red"})
)

这是函数:

   function createSvgElem(options){
        var settings = $.extend({
            }, options);

        if(!$.isEmptyObject(settings.tagName)){
            var el = document.createElementNS('http://www.w3.org/2000/svg', settings.tagName);
            for (var k in settings)
                if(k != "tagName" && k != "text" && settings[k] != "")//If attribute has value
                    el.setAttribute(k, settings[k]);

            if ("text" in settings)
                el.textContent = settings.text; //el.innerText; For IE
            return el;
        }
    }

你可以自己试试:

//Definition: function createSvgElem(options){ var settings = $.extend({ }, options); if(!$.isEmptyObject(settings.tagName)){ var el = document.createElementNS('http://www.w3.org/2000/svg', settings.tagName); for (var k in settings) if(k != "tagName" && k != "text" && settings[k] != "")//If attribute has value el.setAttribute(k, settings[k]); if ("text" in settings) el.textContent = settings.text; //el.innerText; For IE return el; } } //Usage: $(function(){ $("#svg-elem").append( createSvgElem({tagName: "rect", width: 130, height: 500, style: "fill: #000000a3;"}) ) $("#svg-elem").append( createSvgElem({tagName: "text", x: 30, y: 30, text: "ABCD", style: "fill: red"}) ) }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <svg id="svg-elem" width="200" height="200"> </svg>

这是我今天对FF 57的工作:

function () {
    // JQuery, today, doesn't play well with adding SVG elements - tricks required
    $(selector_to_node_in_svg_doc).parent().prepend($(this).clone().text("Your"));
    $(selector_to_node_in_svg_doc).text("New").attr("x", "340").text("New")
        .attr('stroke', 'blue').attr("style", "text-decoration: line-through");
}

使:

发现了一个简单的方法,适用于我所有的浏览器(Chrome 49, Edge 25, Firefox 44, IE11, Safari 5 [Win], Safari 8 (MacOS)):

// Clean svg content (if you want to update the svg's objects) // Note : .html('') doesn't works for svg in some browsers $('#svgObject').empty(); // add some objects $('#svgObject').append('<polygon class="svgStyle" points="10,10 50,10 50,50 10,50 10,10" />'); $('#svgObject').append('<circle class="svgStyle" cx="100" cy="30" r="25"/>'); // Magic happens here: refresh DOM (you must refresh svg's parent for Edge/IE and Safari) $('#svgContainer').html($('#svgContainer').html()); .svgStyle { fill:cornflowerblue; fill-opacity:0.2; stroke-width:2; stroke-dasharray:5,5; stroke:black; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="svgContainer"> <svg id="svgObject" height="100" width="200"></svg> </div> <span>It works if two shapes (one square and one circle) are displayed above.</span>