0

我有以下(人工)DOM:

<div class="something">xxx</div>
<div class="something">
  <div class="essence">yyy</div>
</div>
<div class="something">zzz</div>
<div class="something">
  <div class="essence">111</div>
</div>

然后在$(document).ready我做:

$('.essence').click(function()
{
    $(this).parent().prevAll('.something > .essence').toggle();
    $(this).parent().nextAll('.something > .essence').toggle();
});

它似乎不起作用..

基本上,我想隐藏/显示单击元素parent的所有前后兄弟姐妹,它们不包含与单击元素具有相同类的子元素。

请帮忙。抱歉,如果这看起来含糊不清

4

4 回答 4

3

I highlighted the important parts of your requirement:

I want to hide all preceding and following siblings of clicked element parent, which do not contain a child with the same class as the clicked element.

which would translate to

$(this).parent().siblings().not(':has(> .' + this.className + ')').hide();

or

var className = this.className;
$(this).parent().siblings().filter(function() {
    return $(this).children('.' + className).length === 0;
}).hide();

Explanation for why your code does not work:

.prevAll and .nextAll get the preceding for following siblings of an element, if and only if they match the selector. In your case, all the siblings have class something. The selector doesn't match any of them because it only matches elements with class essence that are children of elements with class something.
I understand what you tried to do, but that's not how those methods work.

于 2013-10-19T19:27:48.923 回答
0

您可以像这样使用 :has() 扩展名:

$(this).parent().siblings('.something:has(.essence)').toggle();

这将选择 .parent() 的所有同级,它们属于 .something 类并包含 .essence 类的后代。您也可以这样做,根据文档可能会更快:

$(this).parent().siblings('.something').has('.essence').toggle();

当我看到它在运行时,这是一种奇怪的行为,所以很难知道它是否正是你所需要的。如果你想切换所有没有 .essence 类的孩子的兄弟姐妹,那么试试这个:

$(this).parent().siblings('.something').not(':has(.essence)').toggle();
于 2013-10-19T20:02:01.233 回答
0

您的代码应更改为如下内容:

$('.essence').click(function()
{
    $(this).parent().siblings().not(':has("> div")').toggle();
});
于 2013-10-19T20:23:34.980 回答
0

You may try this

$('.essence').click(function()
{
    var className = $(this).attr('class');
    $(this).parent().siblings().filter(function(){
        return !$(this).children('.'+className).length;
    }).toggle();
});

DEMO.

于 2013-10-19T19:34:37.477 回答