我有一个与此类似的 HTML 文档。
<html>
<body>
<h1>My Embeded SVG</h1>
<p>This is my html page with some embedded SVG</p>
<svg id="mySVG"></svg>
<textarea id="userbox"></textarea>
<input type="button" value="Replace" OnClick="replaceText()"/>
</body>
</html>
我需要能够用文本区域中用户生成的字符串替换节点。我编写了一个 JavaScript 函数来执行此操作...但是这会替换整个 HTML 文档。
function replaceText(){
var allText = document.getElementById("userbox").value;
var newDoc = document.open("text/svg", "replace");
newDoc.write(allText);
newDoc.close();
}
有什么方法可以替换 SVG 节点吗?
来自用户的文本看起来与此类似。
<svg id="mySVG" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path id="javascript" d="M 448 0 L 1045 0 L 896 40 L 846 159 L 746 378 z" fill="rgba(092,000,214,0.36)" stroke="black"></path></svg>
最佳答案
你可以这样做:
<h1>My Embeded SVG</h1>
<p>This is my html page with some embedded SVG</p>
<div id="svgContainer">
<svg id="mySVG"></svg>
</div>
<textarea id="userbox"></textarea>
<input type="button" value="Replace" OnClick="replaceText()"/>
javascript 是这样的:
// replace below line with the real variable coming from the user input.
var strFromUser = '<svg id="mySVG" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path id="javascript" d="M 448 0 L 1045 0 L 896 40 L 846 159 L 746 378 z" fill="rgba(092,000,214,0.36)" stroke="black"></path></svg>'
var container = document.getElementById("svgContainer");
container.innerHTML = strFromUser;
关于javascript - 使用 javascript 将 html 节点替换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899943/