最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create ul li list dynamically in jquery for n level menu? - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Sep 10, 2011 at 16:14 onof 17.4k7 gold badges52 silver badges86 bronze badges asked Sep 10, 2011 at 14:23 suma dharawadsuma dharawad 511 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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/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>
发布评论

评论列表(0)

  1. 暂无评论