假设:

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

为什么我什么都看不到?


当前回答

这是我今天对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");
}

使:

其他回答

我还没见过有人提到这个方法,但是document.createElementNS()在这个实例中很有帮助。

您可以使用普通Javascript将元素创建为具有正确名称空间的普通DOM节点,然后从那里对它们进行jquery化。像这样:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
    circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');

var $circle = $(circle).attr({ //All your attributes });

$(svg).append($circle);

唯一的缺点是您必须使用正确的名称空间单独创建每个SVG元素,否则它将无法工作。

Bobince给出的公认答案是一个简短的、可移植的解决方案。如果您不仅需要添加SVG,而且还需要操作它,那么可以尝试JavaScript库“Pablo”(它是我编写的)。jQuery用户会感觉很熟悉。

您的代码示例将如下所示:

$(document).ready(function(){
    Pablo("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');
});

你也可以动态地创建SVG元素,而不需要指定标记:

var circle = Pablo.circle({
    cx:100,
    cy:50,
    r:40
}).appendTo('svg');

我可以看到圈在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你可以做到这一点。 设置数据类型为'text'。

. ajax({美元 url:“url-to-svg.svg”, dataType: 'text' }) .done(函数(svg) { 让svg_live = $(svg); svg_live。追加(“<圆残雪= " 100 " cy =“50”r =“40”中风=“黑色”笔划宽度=填“2”=“红色”/ > '); $ (' # selector-id ') . html (svg_live); });

替代方案1:原生js insertAdjacentHTML()

如果你根本不考虑切换到原生JavaScript…… 您还可以使用本地javaScript方法insertAdjacentHTML()来获得同样方便的表示法。

  $("#svg")[0].insertAdjacentHTML(
    "beforeEnd",
    '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>'
  );

$("#svg")[0]使你的jQuery对象在原生JS中可选。

替代方案2:编写一个原生js DOMParser()帮助器

mdn web文档:DOMParser.parseFromString()

  function createSvgEl(markup) {
    markup = `<svg xmlns="http://www.w3.org/2000/svg">
  ${markup}</svg>`;
    const svgEl = new DOMParser().parseFromString(markup, "image/svg+xml")
      .documentElement.children[0];
    return svgEl;
  }

jQuery的用法:

  $("#svgXML").append(
    createSvgEl(
      '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>'
    )
  );

Demo

// native js helper function createSvgEl(markup) { markup = `<svg xmlns="http://www.w3.org/2000/svg"> ${markup}</svg>`; const svgEl = new DOMParser().parseFromString(markup, "image/svg+xml") .documentElement.children[0]; return svgEl; } $(document).ready(function() { // works - but will remove existing children $("#svg1").html( '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>' ); // works // $("#svg")[0] makes your jQueryObject selectable in native JS $("#svg")[0].insertAdjacentHTML( "beforeEnd", '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>' ); $("#svgXML").append( createSvgEl( '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>' ) ); // jquery still works! Vanilla doesn't harm! $("#svgXML circle:nth-of-type(2)").attr('fill', 'orange'); //insert after() $("#svgAfter circle").after( createSvgEl( '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>' ) ); //insert after native $("#svgAfterNative circle")[0].insertAdjacentHTML( "afterEnd", '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>' ); }); svg { border: 1px solid red; overflow: visible; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Append via native js insertAdjacentHTML()</p> <svg id="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"> <circle cx="10" cy="10" r="5" fill="green" /> </svg> <p>Append via DOMParser() helper</p> <svg id="svgXML" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px"> <circle cx="10" cy="10" r="5" fill="green" /> </svg> <p>Append via jquery html() - will strip existing child nodes</p> <svg id="svg1" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px"> <circle cx="10" cy="10" r="5" fill="green" /> </svg> <p>Insert after existing element with jQuery after() using DOMParser() helper</p> <svg id="svgAfter" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px"> <circle cx="10" cy="10" r="5" fill="green" /> </svg> <p>Insert after existing element with native js insertAdjacentHTML()</p> <svg id="svgAfterNative" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px"> <circle cx="10" cy="10" r="5" fill="green" /> </svg>

jquery的after()或before()方法也将无法添加SVG DOM(取决于正确的名称空间)元素。

使用前面提到的变通方法也可以解决这个问题。