当 XML 在 IE9 中用 jQuery 解析而不是 Chrome 时缺少 innerHTML

innerHTML missing when XML parsing with jQuery in IE9 but not Chrome

我在一些包含 HTML.

的简单内容上使用 jQuery 的 XML 解析器

使用 jQuery 的 .html() 或标准 javascript .innerHTML 提取完整的 HTML 文本在 Chrome 中工作正常,但不是在 Internet Explorer 9 中。jQuery 的 .text() 在这两种情况下都有效,但我还需要提取 html 标签。

如何让它在 IE9 上也能正常工作?

您可以在这里进行测试: http://jsfiddle.net/199vLsgz/

XML:

<script id="xml_data" type="text/xml">
    <model_data name="The model ">
          <person_responsible></person_responsible>
          <objects>
               <object name="Available B reports" id="obj1" >
                   <description>this is a description <br/> oh look, another line!</description>
               </object>
          </objects>
     </model_data>
</script>

代码:

$(function() {

    var xml = $("#xml_data").text();
    var xmlDoc = $.parseXML(xml);
    $xml = $(xmlDoc);

    var desc = $xml.find("model_data > objects > object[id='obj1'] > description");
    alert(desc.html());

})

Xml 元素没有在 IE 中定义的 innerHTML,它与 jquery 的 html 函数一起使用。

Firstly you need to use CDATA to preserve tags inside xml tags

<description><![CDATA[this is a description <br/> oh look, another line!]]></description>

那你可以尝试使用textContent 属性:

alert(desc[0].textContent); //desc.text() will also work now

您还可以使用类似以下内容正确添加内容:

$('#some-container').html(desc[0].textContent);

$(function() {

    var xml = $("#xml_data").text();
    var xmlDoc = $.parseXML(xml);
    $xml = $(xmlDoc);
    console.log($xml)
    var desc = $xml.find("model_data > objects > object[id='obj1'] > description");
    alert(desc[0].textContent);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script id="xml_data" type="text/xml">
    <model_data name="The model">
          <person_responsible></person_responsible>
          <objects>
               <object name="Available B reports" id="obj1" >
                   <description><![CDATA[this is a description <br/> oh look, another line!]]></description>
               </object>
          </objects>
     </model_data>
</script>