1

I'm using jQuery's XML parser on some simple content that contains HTML.

Extracting the full HTML text using jQuery's .html() or standard javascript .innerHTML works fine in Chrome, but not in Internet Explorer 9. jQuery's .text() works in both cases, but I need the html tags extracted as well.

How can I make it work with IE9 as well?

You can test it out here: 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>

Code:

$(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());

})
4

1 回答 1

2

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

首先,您需要使用 CDATA 将标签保留在 xml 标签中

<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>

于 2015-01-23T16:38:22.593 回答