简体   繁体   English

jQuery not function不能按预期工作

[英]jquery not function is not working as expected

I have used below code to toggle class for div. 我用下面的代码来切换div的类。

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>  
   <div class="members-section " id="as-member"><img 
    src="img/test1.jpg" alt="">
    <span>Join as a new member</span>
  </div>
   <div class="members-section " id="as-student"><img 
    src="img/test2.jpg" alt=""> 
    <span>Join as a student</span>
  </div>
  <div class="members-section "><img src="img/test3,jpg" alt="">
   <span>Upgrade my membership</span>
 </div>
 <div class="members-section test-member">
  <h5>Teest...</h5>
   <ul class="member-options">
    <li><span>Discounts</span></li>
    <li><span>Institute access</span></li>
    <li><span>Library access</span></li>
    <li><span>Market events</span></li>
   </ul>
</div>
<script>        
$(document).ready(function($) {
    $('#as-member').click(function(e){
        $('.members-section').not($(this)).toggleClass('unselected');
    });         
 });
 </script>
</body>
</html>

The above code toggle the unselected class to all other div except current clicked element. 上面的代码将未选择的类切换到除当前单击的元素之外的所有其他div。

So I want the div also should not toggle which is containing the class "test-member" 因此,我希望div也不应切换包含“ test-member”类的对象

Can this be achieved please? 能做到这一点吗? Anyone look into this and update me your thoughts Thanks. 任何人都对此进行调查,并告诉我您的想法,谢谢。

Use an additional not() method that's it. 使用其他的not()方法即可。 Also, you don't need to wrap this to use with not() method since it accepts a DOM element object as an argument. 此外,您不需要换this与使用not()方法,因为它接受一个DOM元素对象作为参数。

$(document).ready(function($) {
  $('#as-member').click(function(e){
    $('.members-section').not(this).not('.test-member').toggleClass('unselected');
    // here -----------------------^^^^^^^^^^^^^^^^^^^------
  });         
});


Or you can add pseudo-class selector :not() with the main selector. 或者,您可以在主选择器中添加伪类选择器:not()

 $(document).ready(function($) { $('#as-member').click(function(e){ $('.members-section:not(.test-member)').not(this).toggleClass('unselected'); // here -----------^^^^^^^^^^^^^^^^^^^^----------------- }); }); 

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

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