suma dharawad
suma dharawad

Reputation: 51

How to create ul li list dynamically in jquery for n level menu?

Following is the code of first level menu items

    <ul>    
    <li><a href="#" >item1</a>    
    <li><a href="#">item2</a> </li>    
    <li><a href="#">item3</a></li>    
    <li><a href="#">item4 </a></li>   
    </ul> 

when user click on item1 submenu with the similar list for ex

     <ul>    
     <li><a href="#" >item11</a>    
     <li><a href="#">item12</a> </li>   
     <li><a href="#">item13</a></li>  
     <li><a href="#">item14 </a></li>   
     </ul> 

should be created, it wil go for n level. I want to write jquery click event for this. Please keep in mind that it will go for n level, dynamically created elements also should handle the same click event. your help will be appreciated. thanks

Upvotes: 4

Views: 5192

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

How about:

$("ul").delegate("li > a", "click", function() {
    var prefix = $(this).text(),
        $newList = $("<ul />");
    for(var i = 1; i <= 4; i++) {
        $newList.append("<li><a href='#'>" + prefix + i + "</a></li>");
    }
    $(this).closest("li").append($newList);
});

Example: http://jsfiddle.net/FLg3L/

Clicking on link "item1" will yield the following HTML:

<ul>    
    <li>
        <a href="#">item1</a>
        <ul>
            <li><a href="#">item11</a></li>
            <li><a href="#">item12</a></li>
            <li><a href="#">item13</a></li>
            <li><a href="#">item14</a></li>
        </ul>
    </li>   
    <li><a href="#">item2</a> </li>    
    <li><a href="#">item3</a></li>    
    <li><a href="#">item4 </a></li>   
</ul>

Upvotes: 7

Related Questions