开发者

closing an unordered list

开发者 https://www.devze.com 2022-12-23 01:19 出处:网络
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:

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. Th开发者_开发问答is 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?


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


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.

0

精彩评论

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