在jQuery中,可以使用CSS选择器来选取DOM元素。当需要选择除特定类之外的所有元素时,可以使用否定伪类选择器(:not()
)。
:not()
选择器// 选择所有不包含"exclude-class"类的元素
$("*:not(.exclude-class)")
// 更精确的写法(避免选择<html>和<head>等元素)
$("body *:not(.exclude-class)")
.not()
方法// 先选择所有元素,然后排除特定类
$("*").not(".exclude-class")
:not()
选择器通常比.not()
方法性能更好,因为选择是在原生CSS层面完成的.not()
方法可能更直观易读.not()
方法可以链式调用,与其他jQuery方法组合使用*
选择器,因为它会匹配所有元素,影响性能$("div:not(.exclude-class)")
比$("*:not(.exclude-class)")
更高效:not()
选择器不会增加选择器的特异性权重// 示例1:为所有非排除元素添加边框
$("body *:not(.no-border)").css("border", "1px solid #ccc");
// 示例2:点击事件绑定,排除特定类元素
$("button:not(.disabled)").click(function() {
alert("按钮被点击");
});
// 示例3:表单提交前验证,排除隐藏字段
$("form").submit(function() {
$("input:not(.exclude-validate):not([type=hidden])").each(function() {
if (!$(this).val()) {
alert("请填写所有必填字段");
return false;
}
});
});
为什么我的:not()
选择器不起作用?
可能原因:
解决方案:
$(document).ready()
中)没有搜到相关的文章