如何隐藏特定的<li>并在单击特定的</li> <li>时显示它?</li>

时间:2013-02-18 02:53:22

标签: jquery

我想要发生的是,我想要隐藏其<li>等于其他parent_id的{​​{1}} <li>的{​​{1}}。并在点击group_id时显示<li>个?

这是我的样本'<li>',它是PHP生成的。

enter image description here

PHP代码:

<ul>

示例输出: enter image description here

2 个答案:

答案 0 :(得分:2)

你可以尝试

$('#navigitions li[parent_id!="1"]').hide();

function hideSubItems(siblings) {
    if(siblings.length == 0) {
        return;
    }

    siblings.each(function(){
        var siblings = $(this).siblings('[parent_id="' + $(this).attr('group_id') + '"]').hide();
        hideSubItems(siblings)
    });
}

$('#navigitions li').click(function(){
        var siblings = $(this).siblings('[parent_id="' + $(this).attr('group_id') + '"]').toggle();
        hideSubItems(siblings)
    });

演示:Fiddle

答案 1 :(得分:1)

var ids = [],
    $li = $('li');

// Collect all group IDs
$li.each(function () {
    var group_id = $.attr(this, 'group_id');
    if ( ! ~$.inArray(group_id, ids) ) ids.push(group_id);
})
// Hide any li whose parent_id is in the ids array
.each(function () {
    if ( ~$.inArray($.attr(this, 'parent_id'), ids) ) $(this).hide();
})
// When an li is clicked, show any li whose parent_id is equal to this group_id
.click(function () {
    $li.filter('[parent_id=[' + $.attr(this, 'group_id') + ']').show();
});