tags:

views:

50

answers:

2

On a website, I want to display the main navigation as an unordered list. After 3 items I want to close that list and open a new one, so it eventually looks something like this:

<div id="navigation">
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <ul>
        <li>4</li>
        <li>5</li>
        <li>6</li>
    </ul>
</div>

The navigation is dynmically generated using jQuery + Ajax. This is what the code I'm using looks like:

$.getJSON("load.php", 
{
     some: value
},   
function(data)
{         
    $.each(data.items, function(i, item)
    {
        $('#navigation').find('ul').append('<li>' + i + '</li>');

        if(i % 3 == 0)
        {
            $('#navigation').find('ul').append('</ul><ul>');
        }
    });
});

Unfortunately, the browser doesn't interpret this right and treats the closing ul tag as a nested object of the first ul. How do I fix this?

+3  A: 

One solution might be to construct the whole html in a string first (untested):

$.getJSON("load.php", 
{
     some: value
},   
function(data)
{         
    var str="<ul>";
    $.each(data.items, function(i, item)
    {
        str+='<li>' + i + '</li>';

        if(i % 3 == 0)
        {
            str+='</ul><ul>';
        }
    });
    str+="</ul>";
    $('#navigation').html(str);
});
David V.
actually this is the preferred way to do it, since it's the fastest and neatest.
kfiroo
You could argue about if it's really the neatest but in regard to speed it is better.
adamse
It works fine. Thanks!
snorpey
+2  A: 

Try this:

$.getJSON("load.php", 
{
     some: value
},   
function(data)
{   
    var curr = $('#navigation').find('ul');

    $.each(data.items, function(i, item)
    {
        curr.append('<li>' + i + '</li>');

        if(i % 3 == 0)
        {
            curr = curr.after('<ul>');
        }
    });
});

It also "caches" the current ul for greater speed.

adamse