【问题标题】:innerHTML missing when XML parsing with jQuery in IE9 but not Chrome在 IE9 而不是 Chrome 中使用 jQuery 解析 XML 时缺少 innerHTML
【发布时间】:2015-01-23 16:13:12
【问题描述】:

我在一些包含 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());

})

【问题讨论】:

    标签: javascript jquery xml innerhtml jquery-xml


    【解决方案1】:

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

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

    &lt;description&gt;&lt;![CDATA[this is a description &lt;br/&gt; oh look, another line!]]&gt;&lt;/description&gt;

    那么你可以尝试使用 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多