jQuery:隐藏所有DIV的多个深度,然后显示一个

时间:2013-08-30 02:12:25

标签: jquery html css children siblings

我有一些简单的标记来绘制一个下拉菜单和几个不同复杂程度的div:

<select class='sel'>
    <option data-opt='a'>show only 'a' boxes</option>
    <option data-opt='b'>show only 'b' boxes</option>
    <option data-opt='*'>show all</option>
</select>

<div class='holder'>
    <div class='a'>
        <div>
            <p>Here is some text (A)</p>
        </div>
        <p>Plus more stuff in here.</p>
    </div>
    <div class='a'>
        <p>More text (A)</p>
    </div>
    <div class='b'>
        <p>Here is other text (B)</p>
        <div><span>There is more in here!</span></div>
    </div>
    <div class='b'>
        <p>Even more text (B)</p>
    </div>
</div>

当用户从下拉列表中选择一个选项时,我想隐藏不匹配的DIV,并只显示匹配的DIV:

$('.sel').change(function() {
    opt = $(this).find(":selected").data('opt');
    console.log('option chosen: '+opt);

    if(opt == '*') { // select all
        console.log('show all');
        $('.holder').show();

    } else { // hide all but this
        $('.holder :not(div'+opt+')').hide();
        $('.holder').find('div'+opt).show();

    }
});

然而,由于某种原因,它不起作用。看起来hide()方法隐藏了每个元素(包括主DIV的子节点/兄弟节点),然后show()方法只显示初始DIV。并且show-all选项根本不起作用。因此存在一些深度问题。我该如何解决这个问题?

JSFiddle:http://jsfiddle.net/pnoeric/FjEBY/3/

2 个答案:

答案 0 :(得分:1)

http://jsfiddle.net/FjEBY/6/就是答案。

您的选择器有点偏离,而您在.位之前忘记了opt

$('.sel').change(function() {

    var opt = $(this).find(":selected").data('opt'),
        all = $('.holder').children('div').show();

    if ( opt !== '*' ) {
      all.not('.' + opt).hide();   
    }

});

答案 1 :(得分:1)

DEMO

$('.sel').change(function () {
    opt = $(this).find(":selected").data('opt');
    console.log('option chosen: ' + opt);
    if (opt == '*') { // select all
        $('.holder').children('div').show()
    } else { // hide all but this
        $('.holder').children('div').show().not('.' + opt).hide();
    }
});

给定一个表示一组DOM元素的jQuery对象,.find()方法允许我们在DOM树中搜索这些元素的后代,并从匹配元素构造一个新的jQuery对象。 .find().children()方法类似,只是后者只在DOM树中向下移动一个级别。

所以如果你在这里使用.children()

会更好

DEMO

var holder = $('.holder').children('div');
$('.sel').change(function () {
    opt = $(this).find(":selected").data('opt');
    console.log('option chosen: ' + opt);
    if (opt == '*') { // select all
        holder.show()
    } else { // hide all but this
        holder.show().not('.' + opt).hide();
    }
});