Can't target specific LI elements using child

2019-07-19 21:11发布

I just can't figure out what I'm doing wrong.

$('ul.list > li:not(.sublist)').click(function() {
  alert("working now");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
  <li>One</li>
  <li class="special">Two</li>
  <li>Three</li>
  <li>
    <ul class="sublist">
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </li>
</ul>

I'm trying to only select the LI elements that descend from the class(.list). Invariably, the children of the class(.sublist) are also activated when I click.Eeverything I click on gives me the alert. This is not what I want. I'm getting frustrated because I know the answer is simple but I just can't figure it out.

I've also tried using this:

$('ul.list li').not('.sublist').click(function(){
    alert('working');
});

1条回答
甜甜的少女心
2楼-- · 2019-07-19 21:31

Use the direct child combinator, >, in order to only select direct children elements:

ul.list > li

But since this still selects the li that contains the .sublist element, use a combination of the :not()/:has() selectors:

$('ul.list > li:not(:has(.sublist))').on('click', function () {
    // ...
});

Example Here

$('ul.list > li:not(:has(.sublist))').on('click', function () {
    alert('working');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
    <li>One</li>
    <li class="special">Two</li>
    <li>Three</li>
    <li>
        <ul class="sublist">
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
    </li>
</ul>

查看更多
登录 后发表回答