简体   繁体   中英

How to append XML content to an HTML element as if it were HTML and apply CSS styles?

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>

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

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.

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

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

Instead of appending an xml element into your html DOM, append the text value of it.

$element.append($layout.html());

Or for multiple children,

$layout.each(function(){
    $element.append($(this).html());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM