从svg字符串中删除元素

时间:2013-01-04 17:00:24

标签: jquery string svg

我有一个svg字符串str="<svg....</svg>"

<svg width="612" height="394" xmlns="http://www.w3.org/2000/svg">
 <g>
  <title>Layer 1</title>
  <rect id="svg_1" height="100" width="77" y="49.25" x="16.75" stroke-width="5" stroke="#000000" fill="#FF0000"/>
  <rect id="svg_2" height="127" width="160" y="176.25" x="343.75" stroke-width="5" stroke="#000000" fill="#FF0000"/>
 </g>
 <g>
  <title>Layer 2</title>
  <rect id="svg_3" height="112" width="174" y="28.25" x="194.75" stroke-width="5" stroke="#000000" fill="#FF0000"/>
  <text transform="matrix(1, 0, 0, 1.07143, 0, -8.80357)" xml:space="preserve" text-anchor="middle" font-family="serif" font-size="24" id="svg_4" y="94.85" x="281.75" stroke-width="0" stroke="#000000" fill="#000000">Hello</text>
  <rect id="svg_5" height="92" width="103" y="20.25" x="422.75" stroke-width="2" stroke="#ff9900" fill="#0000ff"/>
 </g>
</svg>

我想获得其他字符串,但没有元素。如何从第二层删除文本元素?我试过了var fstr = $(str).wrapAll('<div>').find('g:eq(1) text:eq(0)').remove().closest('div').html();但它不起作用。有解决方案吗感谢

1 个答案:

答案 0 :(得分:1)

要返回SVG字符串,您需要使用XMLSerializer (or corresponding equivalents)

var svg = $(str);
svg.children('g:eq(1)').children('text:first').remove();

function serializeXMLNode(xmlNode) {
    if (typeof window.XMLSerializer != "undefined") {
        return (new window.XMLSerializer()).serializeToString(xmlNode);
    } else if (typeof xmlNode.xml != "undefined") {
        return xmlNode.xml;
    }
    return "";
}

var strUpdated = serializeXMLNode(svg[0]);
console.log(strUpdated);

Fiddle Demo