开发者

find the children in jquery

开发者 https://www.devze.com 2022-12-31 11:00 出处:网络
i have a tree structure,there is an unordered list(ul) in that tree.i have li items in it,and in that li items it could be a span or an ul list.

i have a tree structure,there is an unordered list(ul) in that tree.i have li items in it,and in that li items it could be a span or an ul list.

this is one part of my codes :

            <li id="main_li">
                <div class="first_division"></div>
                <span>products</span>
                <ul style="display: block;">
                    <li>
                        <div class="division1"></div>
                        <span>products_cat_1</span>
                        <ul style="display: none;"> 
                            <li>
                                <span>products_cat_1_milk</span>
                            </li>
                        </ul>
                    </li>                   
                    <li>
                        <span>products_yoghurt</span>
                    </li>                   
                    <li>
                        <span>products_butter</span>
                    </li>
                </ul>
            </li>

i want to access li elements in ul t开发者_如何学JAVAag where the parent li id is "main_li",i want to get it done by clicking on the span within li.

how can i do this with jquery?


The CSS selector that matches the li elements under uls whose parent is 'main_li' is

#main_li > ul > li

further to comment below:

To access the ul that is a sibling to a span, you want the next() selector. If you're in a click handler on the span, the span will be this:

var siblingUL = $(this).next('ul');


Attach a click handler to the relevant <span>. Inside the handler function, navigate to the nodes of interest using tree traversal methods.

Some selectors that might be useful here:

[X] > [Y] // select all Y that are children of X
[X] [Y]   // select all Y that are descendants of X

Example)

$("#main_li > span")
// selects:
// <span>products</span>

$("#main_li span")   
// selects:
// <span>products</span>
// <span>products_cat_1</span>
// <span>products_cat_1_milk</span>
// <span>products_yoghurt</span>
// <span>products_butter</span>

Assuming you attach a click handler on <span>products</span>, and inside the click handler you want to navigate to all <li> children that are at the same level as this span, you could do:

$("#main_li > span").click(function() {
    $(this).siblings("ul").children("li").each(function() {
        // do something with each <li>
    });
});


If you have multiple LIs', you should use aclassrather thanideg#main_li`

$(function(){
  $('.main_li span').click(function(){
    $(this).parents('.main_li').find('li').each(function(){
      // your further code here....
    });
  });
});
0

精彩评论

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