我有点困惑为什么我的简单 .not 函数在这里不起作用。
<section class='main'>
<p class='tweets'></p>
<div class='tweet'>
<p class='time'>
<p class='user'>
<p class='message'>
如果我运行这个 .not 代码
$('.tweet').not($('.message')).hide();
每个发推文的 child 都消失了。据我了解,当它运行时,我要求它查看我的选择器 class=tweet
并隐藏每个不符合 class=message
标准的子级,这应该导致 class=message
的任何元素都显示在我的 HTML 文档上,并且在这种情况下 class=time 和 class=user
隐藏所有其他子元素。我对这个执行的理解是否错误?
最佳答案
.not()
从匹配元素集中删除元素。由于 message 是 tweet 的子元素,因此您的查询无法检测到该元素。
您应该将 :not()
与 .find()
一起使用.
演示:
$('.tweet').find(':not(.message)').hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class='main'>
<p class='tweets'></p>
<div class='tweet'>
<p class='time'>10 AM</p>
<p class='user'>user123</p>
<p class='message'>message</p>
</div>
</section>
关于javascript - 不正确使用 JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60699339/