给定定义了自定义命名空间的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>
答案 0 :(得分:1)
我能想出的最好的是
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:foo="hello"><head>
<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 {
var wrap = '<div xmlns:foo="' + $('div')[0].lookupNamespaceURI('foo') + '">'+ xhtml + '</div>';
var el = document.createElement('div');
el.innerHTML = wrap;
$('div')[0].appendChild(el.firstChild.firstChild);
}
catch(e){ alert(e); }
]]></script>
</body></html>
需要一些打包,但似乎可以在IE9,Chrome 21,FF 14和Opera 12中使用。