简体   繁体   English

“:not”选择器不适用于JQuery

[英]“:not” selector doesn't work with JQuery

I want to show/hide a layer when a user clicks on/out a button. 我想在用户单击/退出按钮时显示/隐藏图层。 I have this simple code that you can check here : 我有这个简单的代码,您可以在这里检查:

JQUERY: JQUERY:

jQuery(function(){

    jQuery('button.profile-button').on('click', function() {
        jQuery('.login-sidebar').show();
        console.log("executed show");
    });
    jQuery(':not(button.profile-button)').on('click', function() {
        jQuery('.login-sidebar').hide();
        console.log("executed hide");
    });

});

HTML: HTML:

<button class="profile-button">Profile</button>
<div class="login-sidebar">Login Sidebar</div>    

CSS: CSS:

.login-sidebar { display: none; }

but when I click the button, the console shows me how the two events are fired. 但是当我单击按钮时,控制台将向我显示如何触发这两个事件。 Is it a bug with :not selector? :not选择器是否有bug? or am I doing anything wrong? 还是我做错了什么?

The way to do that is by not using :not , but filtering inside the event handler 做到这一点的方法是不使用:not ,而是在事件处理程序内部进行过滤

jQuery(function($){
   $(document).on('click', function(e) {
     $('.login-sidebar').toggle( $(e.target).closest('.profile-button').length > 0 );
   });
});

FIDDLE 小提琴

尝试$("*:not(button.profile-button)")但是如果DOM中包含很多元素,则选择起来非常昂贵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM