javascript - 使用 javascript 将 html 节点替换为字符串

标签 javascript html svg nodes

我有一个与此类似的 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/

相关文章:

javascript数字01和1之间的区别

html - Safari/IE 图像映射自定义光标无法正常工作

javascript - bxslider javascript slider 不工作

html - 在 html5 中使用 svg 蒙版剪切照片的矩形区域

javascript - Flash : Coming back from another tab in browser, Flash 可以监听某种返回选项卡事件吗?

javascript - 在同一页面上 react 路由器渲染组件

javascript - 我如何判断 Controller 内部是否是从 ng-controller 或路由运行的

html - 文件上传为图片

javascript - 如何使用 javascript 将 css 类分配给 svg 元素的标题?

javascript - 将 SVG 元素拖动到另一个 SVG 元素上