2

问题

给定一个定义了自定义命名空间的 XHTML 文档,

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:foo="hello">…&lt;/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>
4

1 回答 1

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。

于 2012-08-16T00:09:29.713 回答