not()
选择器详解not()
是 jQuery 的过滤方法,用于从匹配的元素集合中排除符合指定条件的元素。它接受一个选择器、DOM 元素、函数或 jQuery 对象作为参数,返回一个新的 jQuery 对象。
$(selector).not(filter)
filter
:可以是选择器字符串、DOM 元素、函数或 jQuery 对象。// 排除所有带有 `.disabled` 类的按钮
$("button").not(".disabled").css("color", "red");
const excludedElement = document.getElementById("exclude");
$("div").not(excludedElement).hide();
// 排除索引为偶数的元素
$("li").not(function(index) {
return index % 2 === 0;
}).addClass("odd");
const $excluded = $(".ignore");
$("p").not($excluded).fadeOut();
not()
未生效原因:
解决:
// 确保 DOM 加载完成
$(document).ready(function() {
$(".item").not(".hidden").show();
});
方法:使用逗号分隔的选择器。
$("div").not(".class1, .class2").remove();
:not()
伪类的区别:not()
是 CSS 伪类,在 jQuery 中可直接使用,但性能稍差。not()
是 jQuery 方法,支持更复杂的逻辑(如函数过滤)。// 等效但 not() 更灵活
$("div:not(.hidden)") // CSS 伪类
$("div").not(".hidden") // jQuery 方法
:not()
。:not()
。not()
会改变后续操作的集合。not()
会改变后续操作的集合。this
指向当前 DOM 元素。this
指向当前 DOM 元素。通过合理使用 not()
,可以高效地操作 DOM 集合,提升代码可读性和性能。