我有疑问,为什么JQuery忽略.not在这段代码中:
$('body').not('#footer').on('click',function(){
if (($('#footer')).is(":visible")) {
$('#footer').fadeOut();
}
});
Run Code Online (Sandbox Code Playgroud)
基本上,我想关闭#footer,但只能点击除#footer之外的其他元素.上面的代码完成了他的工作,但点击#footer也fadeOut这个元素,这是不希望的.
在另一方面,这将工作:
$('div').not('#footer').on('click',function(){
if (($('#footer')).is(":visible")) {
$('#footer').fadeOut();
}
});
Run Code Online (Sandbox Code Playgroud)
现在的缺点是,如果我点击#footer里面的div,这也会关闭它,所以不是完美的解决方案.
我的问题是,我如何能够锁定所有元素来关闭#footer,而不是#footer和他的孩子.
谢谢你的建议.
我使用过这个选择器:$('body').children().not('#footer').on('click',function(){上面这个,现在关闭#footer只有当我点击身体而不#页脚本身.
为什么JQuery在这段代码中忽略了.not
因为你的body元素没有id页脚,但是你的div元素显然有些!
你可以这样做:
$('div:not(#footer)').on('click',function(){
// if we're not a child of footer and footer is visible
if ($(this).parents('#footer').length == 0 && ($('#footer')).is(":visible")) {
$('#footer').fadeOut();
}
});
Run Code Online (Sandbox Code Playgroud)
或者更好的解决方案是:
$('body').on('click',':not(#footer)',function(){
// as above
});
Run Code Online (Sandbox Code Playgroud)
因为这不会将事件绑定到页面上的每个非页脚div.
或者,您可以将所有工作都滚动到委托的选择器中,以使其简洁.
$('body').on('click',':not(#footer,#footer>*)',function(){
$("#footer").fadeOut();
});
Run Code Online (Sandbox Code Playgroud)
请记住,使用这些委托解决方案会产生很大的开销,因为对于页面上的每次单击,处理程序都将运行,而不仅仅是一次,而是针对其event.target每个.parentNodes.
因此,在每种情况下,选择器将运行并遍历到body以查看元素是否在#footer.
这意味着如果你单击一个嵌套了20个元素深度的节点,它将从中开始event.target,遍历这20个节点并看到它不在#footer.然后,它会在再次启动.parentNode的event.target,并穿越了19个节点,则上涨了18,那么17等.
此外,最终.fadeOut()会被多次调用
所以你可以看到整体效率非常低.
也请记住,这些解决方案需要#footer是直接孩子的body.如果之前有一些父元素body,它就会淡出.