我遇到了IE无法正确附加或识别将子节点附加到已解析的XML字符串中的尝试的问题。 Chrome和Firefox了解我要尝试执行的操作。我不知道这是范围问题还是IE和XML的行为。
var dataContainers = $('[data-container]');
var containerXML = $.parseXML('<inlineSubmission><userid>'+userID+'</userid><guid>'+GUID+'</guid><contentField><![CDATA[FlexXML]]></contentField><content><containers></containers></content></inlineSubmission>');
$.each(dataContainers,function (key,value) {
var containerID = $(value).attr('id'),
isVisible = $(value).is(':visible'),
xmlFragment;
xmlFragment = '<container><name>'+containerID+'</name><visible>'+isVisible+'</visible></container>';
$(containerXML).find('containers').append(xmlFragment);
});
console.log(containerXML)
Chrome和Firefox均可正确返回:
<inlineSubmission><userid>55555</userid><guid>22222-222-2-22-222</guid><contentField><![CDATA[FlexXML]]></contentField><content><containers><container><name>heroContainer</name><visible>true</visible><bgcolor>undefined</bgcolor><textcolor>undefined</textcolor><subitem><name>contactInfo</name><visible>none</visible><location>undefined</location></subitem></container><container><name>contentContainer</name><visible>true</visible></container><container><name>cnmContainer</name><visible>true</visible></container><container><name>accountAccessContainer</name><visible>true</visible></container><container><name>promoContainer</name><visible>true</visible></container><container><name>contactContainer</name><visible>true</visible></container></containers></content></inlineSubmission>
当IE返回原始变量值时:
<inlineSubmission><userid>55555</userid><guid>22222-222-2-22-222</guid><contentField><![CDATA[FlexXML]]></contentField><content><containers /></content></inlineSubmission>
任何帮助,将不胜感激!
最佳答案
尝试用$(containerXML.documentElement)
替换$(containerXML)
。$(containerXML)
返回#document
,其中context
为document
,例如;$(document).append("<p>abc</p>")
不会将<p>abc</p>
追加到<html>
或<body>
元素,并且可能返回错误:TypeError: Cannot read property 'createDocumentFragment' of null
。$(containerXML.documentElement)
返回<inlinesubmission>
元素,其中context
为inlinesubmission
var userID = "abc", GUID = 123, containerID = 456, isVisible = true;
var xmlFragment = '<container><name>'
+containerID+'</name><visible>'
+isVisible+'</visible></container>';
var containerXML = $.parseXML('<inlineSubmission><userid>'
+userID+'</userid><guid>'
+GUID+'</guid><contentField><![CDATA[FlexXML]]>'
+'</contentField><content><containers></containers>'
+'</content></inlineSubmission>');
console.log($(containerXML)
, $(containerXML.documentElement).find("containers"));
$(containerXML.documentElement).find("containers").append(xmlFragment);
$("body").append($(containerXML.documentElement));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>