2013-04-09 68 views
1

我有一个HTML文件,该文件类似于这样的字符串替换HTML节点。与使用JavaScript

<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> 

我需要能够用textarea中用户生成的字符串替换节点。我写了一个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> 
+2

的HTML标签应该是BODY标签之外。 – 2013-04-09 10:52:32

+0

对不起......一个错字问这个问题 – CJH 2013-04-09 10:56:03

+0

不应该allText'的'值从“USERBOX”上牵拉,而不是“savebox”的时候? – LuigiEdlCarno 2013-04-09 10:58:28

回答

1

你可以做这样的事情:

<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; 
+0

与我所说的有何不同? – 2013-04-09 11:04:24

+0

你为什么这样评论?这是一个社区网站。 – wmfairuz 2013-04-09 11:05:32

+0

像什么?我只是好奇你还有什么改变。 – 2013-04-09 11:07:01

0

你不应该使用write()writeln()页面已经呈现后。这将确实清除整个页面。

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

ps。当心你有textarea id为userbox,但在JS使用saveBox