如何钓鱼:一遍又一遍地使用一个函数,这样您就不必一直想办法解决这个问题。我为我的网络平台保留了大量高度可重用的函数。
有一个警告:我编码严格,所以如果它是单个元素,只需在任何地方添加 xmlns="http://www.w3.org/1999/xhtml" 属性/值。如果您需要多个元素,您将需要一个包含所有具有xmlns="http://www.w3.org/1999/xhtml" XML 命名空间的子元素的父元素。我用这些东西效率很高,因为它是严格的代码。
本文底部需要两个必备功能。
xml_add('before', id_('element_after'), '<input type="button" xmlns="http://www.w3.org/1999/xhtml" />');
xml_add('after', id_('element_before'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');
xml_add('inside', id_('element_parent'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');
添加多个元素(命名空间只需要在父元素上):
xml_add('inside', id_('element_parent'), '<div xmlns="http://www.w3.org/1999/xhtml"><input type="text" /><input type="button" /></div>');
动态可重用代码:
function id_(id) {return (document.getElementById(id)) ? document.getElementById(id) : false;}
function xml_add(pos, e, xml)
{
e = (typeof e == 'string' && id_(e)) ? id_(e) : e;
if (e.nodeName)
{
if (pos=='after') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e.nextSibling);}
else if (pos=='before') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
else if (pos=='inside') {e.appendChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true));}
else if (pos=='replace') {e.parentNode.replaceChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
//Add fragment and have it returned.
}
}