无法使用子选择器定位特定的LI元素 [英] Can't target specific LI elements using child selectors

查看:114
本文介绍了无法使用子选择器定位特定的LI元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是弄不清楚我在做什么错.

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>

我试图仅选择从class(.list)继承的LI元素.当我单击时,class(.sublist)的子级也总是被激活,我单击的所有内容都会提醒我.这不是我想要的.我很沮丧,因为我知道答案很简单,但我无法弄清楚.

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.

我也尝试过使用它:

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

推荐答案

使用直接子组合器> ,以便仅选择直接子元素:

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

ul.list > li

但是由于这仍然会选择包含.sublist元素的li,因此请使用 :not() / :has() 选择器:

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

此处示例

$('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>

这篇关于无法使用子选择器定位特定的LI元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆