开发者

Group javascript xml output by letters or other attributes

I have an xml document that looks something like this

<?xml version="1.0" encoding="UTF-8"?>
<mapPoints>
<annotation cat="A" title="123" type="pointer"/>
<annotation cat="A" title="333" type="pointer"/>
<annotation cat="B" title="555" type="pointer"/>
</mapPoints>

I am parsing the XML into my javascript document. Now, I want to group the output of my xml file in different divs base on the cat in the xml so that the markup would look something like this

<div class="A">
<ul>
<li>123开发者_如何学运维 cat A</li>
<li>333 cat A</li>
</ul>
</div>
<div class="B">
<ul>
<li>555 cat B</li>
</ul>
</div>

My parsing is working properly but I don't know how I would group the entries and then output them into different divs. The solution needs to be dynamic since it could be a lot of categories.


Using jQuery and assuming you have your xml in a variable xml, try this:

$(xml).find('mapPoints annotation').each(function() {
    var class = $(this).attr('cat');
    if ($('div.' + class).length == 0) {
        $('#annotations').append('<div class="' + class + '"><ul></ul></div>');
    }
    $('div.' + class + ' ul').append(getLiFromXml(this));
});

getLiFromXml is a function that returns <li>123 cat A</li> for <annotation cat="A" title="123" type="pointer"/> - hopefully, you can easily write it.

UPDATE

Updated the code to add a div first. I assumed that you store all your divs in a container (div, td, whatever...) with id="annotations"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜