问题
给定一个定义了自定义命名空间的 XHTML 文档,
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:foo="hello">…</html>
如何使用 jQuery(或 vanilla JavaScript)添加具有引用该命名空间的属性的元素,指定为字符串:
var newElement = '<p foo:bar="please">add me</p>';
你试过什么?
var xhtml = '<p foo:bar="no">two</p>';
try { $('div').append(xhtml); }
catch(e){ alert(e); }
// [FFv14] "An invalid or illegal string was specified" code: "12"
// [Chromev21] Error: SYNTAX_ERR: DOM Exception 12
// [IE9] DOM EXception: SYNTAX_ERR (12)
try { $('div')[0].innerHTML += xhtml; }
catch(e){ alert(e); }
// [FFv14] Works!
// [IE9] Works!
// [Chromev21] Error: SYNTAX_ERR: DOM Exception 12
测试页(托管)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:foo="hello"><head>
<meta http-equiv='Content-Type' content='Type=text/html; charset=utf-8'/>
<title>Using JS to add element referencing custom namespace</title>
</head><body>
<div><p foo:bar="yes">one</p></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript"><![CDATA[
var xhtml = '<p foo:bar="no">two</p>';
try { $('div').append(xhtml); }
catch(e){ alert(e); }
try { $('div')[0].innerHTML += xhtml; }
catch(e){ alert(e); }
]]></script>
</body></html>