gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:19:24 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com