简体   繁体   中英

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

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>

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