简体   繁体   English

如何使用javascript动态更改html中svg的文本内容

[英]How to dynamically change the text content of svg in html with javascript

My requirement is to remove the text element from g and another text element. 我的要求是从g和另一个文本元素中删除文本元素。 But when I run this code, text which written is removed perfectly but adding new text tag is not showing. 但是当我运行此代码时,写入的文本被完全删除但添加新文本标签未显示。 When I open the developer section of Chrome, it shows my added text tag but it is not showing in view. 当我打开Chrome的开发者部分时,它会显示我添加的text标记,但它未显示在视图中。 And when I update any thing from developer section of chrome then DOM again reload and my new text would be shown in view. 当我从chrome的开发人员部分更新任何内容时,DOM再次重新加载,我的新文本将在视图中显示。

<!DOCTYPE html>  

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    <svg id="t">
    <g>
        <text x="10" y="10">hello</text>
    </g>
    </svg>
    <script>
            var s = document.getElementById('t');
            var g = s.childNodes[1];
            console.log(g.childNodes[1].remove());//remove text must in my case
            var txt = document.createElement('text');
            txt.setAttribute('x', '10');
            txt.setAttribute('y', '10');
            var t = document.createTextNode("This is a paragraph.");
            txt.appendChild(t);
            g.appendChild(txt);

    </script>        
    </body>
</html>

If you want to change the text you don't have to remove the entire element and recreate it. 如果要更改文本,则不必删除整个元素并重新创建它。 You could simply change the textcontent by selecting the text element and set new content to it like following: 您可以通过选择文本元素并将新内容设置为它来更改textcontent,如下所示:

document.getElementById('t').childNodes[1].childNodes[1].innerHTML= "This is a paragraph";

See working example here: 见这里的工作示例:

 <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <svg id="t"> <g> <text x="10" y="10">hello</text> </g> </svg> <script> document.getElementById('t').childNodes[1].childNodes[1].innerHTML= "This is a paragraph";//remove text must in my case </script> </body> </html> 

You have to use createElementNS when creating SVG elements 创建SVG元素时必须使用createElementNS

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

FIDDLE 小提琴

如果你在d3中工作,你可以简单地做d3.select('#svgTextId').html(newHTML)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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