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

Replace a html node with a string using javascript

本文关键字:替换 字符串 节点 html javascript 使用      更新时间:2023-09-26

我有一个看起来与此类似的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;

您不应该在页面呈现后使用write()writeln()。这将清除整个页面。

您需要做的是将SVG放在<DIV>或其他一些标签中。然后将getElementById()改为DIV,并将其innerHTML改为用户输入的值。

p。注意你有textarea id userbox,但在JS中你使用saveBox