[英]Error: uncaught exception: [Exception... "An invalid or illegal string was specified"
[英]appending entire svg to dom element leads to Exception... "String contains an invalid character" code: "5"
我想将整个 svg 元素附加到 DOM 的无子元素中。 我尝试了 d3-style 和 common 样式,两者都导致我出现此错误:
[Exception... "String contains an invalid character" code: "5" nsresult: "0x80530005 (InvalidCharacterError)" location: "<unknown>"]
我如何正确附加它?
// with d3
var dropTargetsDiv = d3.select(".droptargets").html("");
dropTargetsDiv.append(svgPic);
// without d3
var dropTargetsDiv = window.document.getElementById("canvas").parentNode;
dropTargetsDiv.innerHTML="";
dropTargetsDiv.appendChild(window.document.createElement(svgPic));
//the svg content is taken from a text area...
var svgPic = scope.$parent.export;
//and looks fine
<svg id="canvas"><g id="dashboard-content"><rect id="dropPanel"></rect></g></svg>
// the structure
<div class="droptargets"...
<svg id="canvas"...
<g id="dashboard-content...
D3 的.append()
不接受要追加的元素的内容。 引用文档:
附加具有指定名称的新元素作为当前选择中每个元素的最后一个子元素 [...] 可以将名称指定为常量字符串或返回要附加的 DOM 元素的函数。
所以要附加一个 SVG 元素,你应该做
var svg = dropTargetsDiv.append("svg");
然后填充节点的内容,即添加g
元素和可能存在的任何其他内容。
通过dropTargetsDiv.innerHTML=mySVGText
将 svg 文本插入到您的 SVG DIV 中。 这将完全取代以前的。
示例如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body style='font-family:arial'>
<center>
<div style='width:90%;background-color:gainsboro;text-align:justify;padding:10px;border-radius:6px;'>
Replace DIV.innerHTML with new SVG text
</div>
<br />New SVG Source:<br />
<textarea id=svgNewSourceValue style='font-size:110%;font-family:lucida console;width:90%;height:100px'>
<svg id="mySVG2" width="400" height="400" xmlns="http://www.w3.org/2000/svg" >
<rect width=150 height=100 x=100 y=100 fill=blue />
</svg>
</textarea>
<div id="svgDiv" style='background-color:lightgreen;width:400px;height:400px;'>
<svg id="mySVG1" width="400" height="400" xmlns="http://www.w3.org/2000/svg" >
<circle r=150 cx=200 cy=200 fill=red />
</svg>
</div>
<center><button onClick=replaceSVG()>Replace SVG</button></center>
<br />SVG Source:<br />
<textarea id=svgSourceValue style='font-size:110%;font-family:lucida console;width:90%;height:100px'>
</textarea>
<br />Javascript:<br />
<textarea id=jsValue style='border-radius:26px;font-size:110%;font-weight:bold;color:midnightblue;padding:16px;background-color:beige;border-width:0px;font-size:100%;font-family:lucida console;width:90%;height:200px'></textarea>
</center>
<script id=myScript>
function replaceSVG()
{
svgDiv.innerHTML=svgNewSourceValue.value
svgSourceValue.value=svgDiv.innerHTML
}
</script>
<script>
document.addEventListener("onload",init(),false)
function init()
{
svgSourceValue.value=svgDiv.innerHTML
jsValue.value=myScript.text
}
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.