如何将XML内容附加到HTML元素,如同它是HTML并应用CSS样式? [英] How to append XML content to an HTML element as if it were HTML and apply CSS styles?

查看:197
本文介绍了如何将XML内容附加到HTML元素,如同它是HTML并应用CSS样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为'layouts.xml'的XML文件,如下所示:

I have an XML file called 'layouts.xml' that looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<layouts>
   <layout id="layoutA">
     <div class="layout typeA">
       <div class="class1"></div>
       <div class="class2"></div>
     </div>
   </layout>
   <layout id="layoutB">
     <div class="layout typeB">
       <div class="class1"></div>
       <div class="class3"></div>
     </div>
   </layout>
</layouts>

XML中的每个'layout'元素都包含一组div元素,网页动态地作为HTML。我试图这样做:

Each 'layout' element in the XML contains a set of div elements that I want to insert into my webpage dynamically as HTML. I am attempting to do this like so:

$.fn.myFunc = function () {
   var url = "layouts.xml";
   var $element = $(this);  // element to append to

   $.get(url, function (responseXml) {
      var $layout = $(responseXml).find('#layoutA').children();
          $element.empty();
          $element.append($layout);
   });
}

$('div#myDiv').myFunc();

这会将标记插入我的网页,但是我为这些动态插入的div元素创建的CSS样式不适用。样式适用于已存在的HTML元素,但不适用于任何动态添加的内容。我已经使用在线w3c服务验证了CSS,XML和生成的HTML。

This inserts the markup into my webpage, but the CSS styles I have created for these dynamically inserted div elements are not being applied. The styles are applied to HTML elements that already exist, but not to any dynamically added content. I have validated the CSS, XML and resulting HTML using the online w3c services.

我真的很感谢一些帮助,让这些CSS样式应用!谢谢。

I would really appreciate some help getting these CSS styles to apply! Thank you.

推荐答案

切换到$ .ajax()方法并指定dataType为'text'以附加XML,如下所示:

After switching to the $.ajax() method and specifying a dataType of 'text', I was able to append the XML as shown below:

var $element = $('div#myDiv');

$.ajax({
    url: 'layouts.xml',
    dataType: 'text',
    success: function (data) {
        var $layout = $(data).find('.layout typeA');
        $element.empty();
        $element.append($layout.html());
    }
});

As Tap指出,我需要将XML附加为文本。但是,我不能通过$ .text()或$ .html()方法从XML文档对象获取XML作为文本,所以我不得不更改AJAX请求,所以它会将XML作为文本(而不是作为XML文档对象)。

As Tap pointed out, I needed to append the XML as text. However, I could not get the XML as text from the XML document object via the $.text() or $.html() methods, so I had to change the AJAX request so it would give me the XML as text (instead of as an XML document object).

这篇关于如何将XML内容附加到HTML元素,如同它是HTML并应用CSS样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆