[英]Can't target specific LI elements using child selectors
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). 我试图仅选择从class(.list)继承的LI元素。 Invariably, the children of the class(.sublist) are also activated when I click.Eeverything I click on gives me the alert.
当我单击时,class(.sublist)的子级也总是被激活。单击的所有内容都会给我警报。 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');
});
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: 但是,由于这仍然会选择包含
.sublist
元素的li
,因此.sublist
使用:not()
/ :has()
选择器的组合:
$('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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.