【问题标题】:jQuery: hide multi-depth all DIVs, then show onejQuery:隐藏多深度所有DIV,然后显示一个
【发布时间】:2013-08-30 02:12:24
【问题描述】:

我有一些简单的标记来绘制下拉菜单和一些复杂程度不同的 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。并且显示全部选项根本不起作用。因此,深度存在一些问题。我该如何解决这个问题?

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

【问题讨论】:

  • 别忘了选择你使用的答案:)

标签: jquery html css children siblings


【解决方案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();   
    }

});

【讨论】:

  • 我需要调整我的一秒钟我没有意识到我在其中一个框中漏掉了一个句子
  • 将 Tushar 的和我的结合起来,制作一个更简单的块
【解决方案2】:

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();
    }
});

【讨论】:

  • @Eric 这个代码比你的快。当您使用 .find() 但您的目的可以与 .children() 一起使用时,请参阅此图片 --> tinyurl.com/2clyrbz
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 2015-10-07
  • 2013-03-17
  • 2015-07-21
相关资源
最近更新 更多