问题
The Question
Given an XHTML document with a custom namespace defined,
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:foo="hello">…</html>
how can I use jQuery (or vanilla JavaScript) to add an element with an attribute referencing that namespace, specified as a string:
var newElement = '<p foo:bar="please">add me</p>';
What Have You Tried?
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
Test Page (Hosted)
<!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>
回答1:
Best I can come up with is
<!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>
Needs a bit of packaging up, but seems to work in IE9, Chrome 21, FF 14, and Opera 12.
来源:https://stackoverflow.com/questions/11972852/add-xhtml-element-referencing-existing-namespace