开发者

What's the correct jQuery selector for this? I want to get all tr with attr x, which are directly beneath (same level) given tr

I'm currently working on something like a tree, and I want to be able to fold/unfold children. I guess the most easy way to get this is by using nested lists, but I can't use them because I don't have access to the HTML code. This is the relevant simplified HTML code:

<table>
    <tbody>
        <tr rel="1"><td><a href="#" id="fold">fold</a> item 1</td></tr>
        <tr rel="2"><td><a href="#" id="fold">fold</a> item 1.1</td></tr>
        <tr rel="2"><td><a href="#" id="fold">fold</a> item 1.2</td></tr开发者_JS百科>
        <tr rel="1"><td>item 2</td></tr>
        <tr rel="1"><td><a href="#" id="fold">fold</a> item 3</td></tr>
        <tr rel="2"><td><a href="#" id="fold">fold</a> item 3.1</td></tr>
        <tr rel="3"><td>item 3.1.1</td></tr>
        <tr rel="3"><td>item 3.1.2</td></tr>
</tbody>
</table>

As you can see, no nested items, but there are 'levels' available, so I guess it should be possible to do what I have in mind. The fold/unfold part is working, f.e. when I click fold on item 1, items with rel >= 2 are hidden. But that's not what I want; I only want to fold the items which rel is higher than the one where I clicked fold, and want to hide all of them until I reach an element which rel is lower or equal to the current rel.

For example, when I click fold in item 1, item 1.1 and 1.2 should be hidden, but item 3.1 should stay visible.

Is there anyone that can help me getting started? Thanks.

Bjorn


I do not think that you can achieve this with a single selector. This is my approach: http://jsfiddle.net/RrnDG/1/ Note that i changed your id="fold" to class="fold", since having multiple IDs with the same value is invalid. An ID is meant to be unique.

What i am doing here is (basically):

  • get level of the clicked row
  • traverse all following rows. for each do:
    • check if level is higher (e.g. deeper nested); if true, toggle visibility, otherwise abort traversing


something like this should work

$("#fold").click(function()
{
    var _current = $(this).parent().parent();
    var _level = _current.attr('rel');

    _current.nextAll().each(function()
    {
        if($(this).attr('rel') > _level){
            $(this).hide();
        }else{
            // Nested children stopped here, we don't continue
            return false;
        }
    });        
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜