动态更改SVG元素,

时间:2013-10-22 06:59:49

标签: javascript jquery html dom svg

我有这个HTML:

<span class="pop">
    <svg version="1.1"  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="200px" height="180px" viewBox="-18.25 -18.75 200 180" enable-background="new -18.25 -18.75 200 180" xml:space="preserve">
        <text class="triangle-text" transform="matrix(1 0 0 1 63 -5.25)"  font-family="'HelveticaNeue'" font-size="11">text</text>
        <text class="triangle-text" transform="matrix(1 0 0 1 51 156.75)"  font-family="'HelveticaNeue'" font-size="11">text1</text>
        <text class="triangle-text" transform="matrix(1 0 0 1 -13.4998 77)"  font-family="'HelveticaNeue'" font-size="11">text2</text>
        <text class="triangle-text" transform="matrix(1 0 0 1 126 77)" font-family="'HelveticaNeue'" font-size="11">text3</text>
        <g>
            <polygon class="sl" fill="#F4f2f3" points="" />
        </g>
    </svg>
</span>

然后我从js准备另一个SVG内容并使用jquery的replaceWith()我替换原始的SVG。它在Firebug中被替换,但它不会显示在浏览器中。

我的JS:

   pop = '<svg xml:space="preserve" enable-background="new -18.25 -18.75 200 180" viewBox="-18.25 -18.75 200 180" height="180px" width="200px" y="0px" x="0px" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" version="1.1"><text haschanged="true" class="triangle-text" transform="matrix(1 0 0 1 63 -5.25)"  font-family="HelveticaNeue" font-size="11">Chiara</text>\n\
          <text class="triangle-text" transform="matrix(1 0 0 1 51 156.75)"  font-family="HelveticaNeue" font-size="11">Non chiara</text>\n\
          <text class="triangle-text" transform="matrix(1 0 0 1 -13.4998 77)"  font-family="HelveticaNeue" font-size="11"><tspan x="10" y="10">Non</tspan><tspan x="10" y="20">concordo</tspan></text>\n\
          <text class = "triangle-text" transform = "matrix(1 0 0 1 -13.4998 77)"  font - family = "HelveticaNeue" font - size = "11" >Concordo</text>\n\
          <g>';
      for (key in triangles) {
        pop += '<polygon class = "sl" index = "' + key + '" understanding = "' + triangles[key].a + '" comprehension = "' + triangles[key].c + '" fill = "' + colors[resp.msg[key]] + '" points = "' + triangles[key].points + '" msg = "' + triangles[key].msg + '" />';
      }
      pop += '</g></svg>';

我这样绑定:

$('.pop').children('svg').replaceWith(pop);

我在论坛上遇到了与此相关的问题,但没有找到解决方案。

2 个答案:

答案 0 :(得分:0)

替换后尝试此操作:

$('.pop').html($('pop').html());

答案 1 :(得分:0)

我很确定您的问题是您创建SVG片段的方式。您不能像创建这样的jQuery一样创建SVG,就像创建HTML片段一样。 jQuery不会在正确的命名空间中创建SVG。

您需要手动创建SVG DOM-DOM元素。或者使用jQuery SVG或d3.js等插件。