添加引用现有命名空间的XHTML元素 [英] Add XHTML element referencing existing namespace
本文介绍了添加引用现有命名空间的XHTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于定义了自定义命名空间的XHTML文档,
Given an XHTML document with a custom namespace defined,
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:foo="hello">…</html>
如何使用jQuery(或vanilla JavaScript)添加具有引用该命名空间的属性的元素,指定为字符串:
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>
推荐答案
我能想出的最好的是
<!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和歌剧12。
Needs a bit of packaging up, but seems to work in IE9, Chrome 21, FF 14, and Opera 12.
这篇关于添加引用现有命名空间的XHTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文