简体   繁体   中英

Change external SVG text with javascript

I'm having an issue changing the text in an external SVG. I've found a number of solutions listed here but none of them have worked.

Adding a listener:

document.getElementById('id1').addEventListener('onload', func);

The function:

function func () {

    var ele = document.getElementById('id1'),
        svg = ele.contentDocument,
        p = svg.getElementById('id2');

    alert(p.textContent);
    p.textContent = 'test';

}

The first time I load it, p returns null. On the second load the alert returns the correct text within the SVG text element but the text is not updated by the next statement.

Why is it not working on the first load and why is the text not changing

<svg height="90" width="200">
  <text x="10" y="20" style="fill:red;">Several lines:
    <tspan x="10" y="45">First line.</tspan>
    <tspan x="10" y="70">Second line.</tspan>
  </text>
  <text x="40" y="60">more text</text>
  <text>will not display as x and y are missing</text>
</svg>

You need to set the x and y attribute for an element to be displayed. Also the alert should happen after you set the value of the text element:

p.textContent = 'test';
alert(p.textContent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM