动态更改 SVG 文件的文本

Muk*_*pta 5 javascript css svg

我有包含代码的外部 SVG 文件

<g
     inkscape:groupmode="layer"
     id="layer9"
     inkscape:label="score"
     style="display:inline">
     <text
        xml:space="preserve"
        style="font-style:normal;font-weight:normal;font-size:22.5px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
        x="100.3568906"
        y="20.353357"
          id="text5833"
        sodipodi:linespacing="125%"><tspan
          sodipodi:role="line"
          id="tspan5834"
          x="300.3568906"
          y="20.353357">Score</tspan></text>

  </g>
Run Code Online (Sandbox Code Playgroud)

我需要从 JS 文件动态更改文本 Score,我已经尝试过但无法动态更改文本。我试过的是:-

var list = layerNamed('score').getElementsByTagName("g");
var textNode = document.createTextNode("Score:-1");
list.appendChild(textNode);
Run Code Online (Sandbox Code Playgroud)

Soo*_*ran 9

您可以使用以下代码更改现有text元素内的文本。

document.getElementById('textid').textContent = "new text";

下面的工作示例:

function changeText()
{
  document.getElementById('textid').textContent = "new text";
}
Run Code Online (Sandbox Code Playgroud)
<svg height="30" width="200">
  <text id="textid" x="0" y="15" fill="red">I love SVG!</text>
  Sorry, your browser does not support inline SVG.
</svg>

<button onclick="changeText()">Click here to change text</button>
Run Code Online (Sandbox Code Playgroud)