当您将标记字符串传递给$
时,它将使用<div>
(或其他适合于<tr>
等特殊情况的容器)上的浏览器innerHTML
属性解析为HTML.innerHTML
无法解析SVG或其他非HTML内容,即使它可以解析,也无法判断<circle>
应该在SVG名称空间中.
innerHTML
在SVGElement上不可用,它只是HtmleElement的一个属性.目前也没有innerSVG
属性或其他方式(*)将内容解析为SVGElement.因此,应该使用DOM样式的方法.jQuery不能让您轻松访问创建SVG元素所需的命名空间方法.实际上,jQuery根本不是为SVG设计的,许多操作可能会失败.
HTML5promise ,在future 的普通HTML(text/html
)文档中使用<svg>
而不使用xmlns
.但这只是一个解析器破解(**),SVG内容仍然是SVG名称空间中的SVG元素,而不是HTMLElements,因此您将无法使用innerHTML
,即使它们是HTML文档的一部分.
但是,对于今天的浏览器,您必须使用XHTML(适当地用作application/xhtml+xml
;保存时使用.xhtml文件扩展名进行本地测试)才能使SVG工作.(不管怎样,这是有意义的;SVG是一个完全基于XML的标准.)这意味着您必须转义脚本挡路中的<
个符号(或包含在CDATA节中),并包含XHTMLxmlns
声明.示例:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
</head><body>
<svg id="s" xmlns="http://www.w3.org/2000/svg"/>
<script type="text/javascript">
function makeSVG(tag, attrs) {
var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs)
el.setAttribute(k, attrs[k]);
return el;
}
var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
document.getElementById('s').appendChild(circle);
circle.onmousedown= function() {
alert('hello');
};
</script>
</body></html>
*:虽然有DOM Level 3 LS's parseWithContext,但浏览器支持非常差.编辑添加:然而,虽然不能将标记注入SVGElement,但可以使用innerHTML
将新的SVGElement注入HtmleElement,然后将其传输到所需的目标.不过可能会慢一点:
<script type="text/javascript"><![CDATA[
function parseSVG(s) {
var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
var frag= document.createDocumentFragment();
while (div.firstChild.firstChild)
frag.appendChild(div.firstChild.firstChild);
return frag;
}
document.getElementById('s').appendChild(parseSVG(
'<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
));
]]></script>
**:我讨厌HTML5的作者们似乎害怕XML,并决心把基于XML的功能塞进HTML的烂摊子里.XHTML多年前就解决了这些问题.