jQuery:选择没有特定类的所有子元素

时间:2018-12-10 13:08:24

标签: javascript jquery html

我具有以下HTML结构:

sudo apt-get install build-essential

以及直到现在的以下jQuery代码:

<li class="menu-has-children"><a href="#">Main</a>
<ul class="some-menu">
    <li><a href="#">Some Link 1</a></li>
    <li class="not-wanted"><a href="#">Some Link 2</a></li>
    <li><a href="#">Some Link 3</a></li>
</ul>
</li>

我的目标是显示$(document).on('click', '.menu-has-children a', function(e) { $(this).nextAll('ul').eq(0).slideToggle(); }); 之后的下一个li元素中的所有ul元素,但不包括附加了this类的锂元素。我该如何实现?

到目前为止,我只显示了以上代码所暗示的所有not-wanted元素,但是我不知道如何排除不需要的元素。

3 个答案:

答案 0 :(得分:1)

您可以使用jQuery not函数:

$('li').not('.not-wanted')

请参见jQuery not() documentation

对于您的情况,可能看起来像这样:

$(document).on('click', '.menu-has-children a', function(e) {
  $(this).nextAll('ul').find('li').not('.not-wanted').slideToggle();
});

这与使用CSS3 not限定符可获得相同的结果,但可能更易于阅读。我无法保证它的速度与CSS3 not相比如何-需要进行测试。

答案 1 :(得分:0)

您可以使用CSS3 not选择器:

$(document).on('click', '.menu-has-children a', function(e) {
  $(this).nextAll('ul').find("li:not(.not-wanted)").slideToggle();
});

答案 2 :(得分:0)

做这样的事情,

$(document).on('click', '.menu-has-children a', function(e) {
  $('li:not(.not-wanted)', $(this).next('ul')).slideToggle();
});

:not()选择器将帮助您从整个选择中排除一组元素。

DEMO

相关问题