简体   繁体   中英

jQuery .NOT() $(this) or $(this).parent()

I have the below code and I'm trying to stop if from firing the .hide() on two occasions, currently using .not() . The two occasions are:

  • $(this).parent().closest(".HoverChild")
  • and
  • $(this).children(".HoverChild")

EDIT: Because it's not using the second $(this) it's hiding the child element then showing it again.

 $(".HoverContainer").on("hover click",function (e) { $('.HoverChild').not( $(this).parent().closest(".HoverChild"), $(this).children(".HoverChild") ).hide(); if ($(".HoverContainer").is(e.target)){e.stopPropagation();} $(this).children('.HoverChild').stop(true,true).slideToggle(100); }); $("body").on("hover click",function (e){ if (!$(".HoverContainer").is(e.target) && $(".HoverContainer").has(e.target).length === 0) { $(".HoverContainer").children('.HoverChild').hide(); }}); $(".HoverChild").on("hover click",function (e) { e.stopPropagation(); }); 
 html, body{ WIDTH: 100%; HEIGHT: 100%} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <span class="HoverContainer" style="Float:Left;"> <img src="" alt="View Categories" style="width:20px;height:20px;"> <div class="HoverChild" style="display: none;"> <ol class="top-nav" > <li class="HoverContainer" >Parent <ul class="HoverChild" style="display: none;"> <li><a href="javascript:void(0);">Sub 1</a></li> <li><a href="javascript:void(0);">Sub 2</a></li> </ul> </li> </ol> </div> </span> 

Your help on this would be greatly appreciated. Many thanks.

glenn2223

not() only accepts a single argument. You have three options to achieve what you would like. The first one is to pass an array into the not() function as follows:

$('.HoverChild').not([
    $(this).parent().closest('.HoverChild'),
    $(this)
]).hide();

Alternatively, you need to filter down the results after the first parameter of the not() function is evaluated. You can either do that by chaining another not() function to the filter, for example:

$('.HoverChild').not( $(this).parent().closest('.HoverChild') )
                .not ($(this) )
                .hide();

Or you can combine $(this).parent().closest('.HoverChild') and $(this) into a single jQuery collection using add() , and then evaluate not() on that:

var $not = $(this).parent().closest('.HoverChild').add( $(this) );
$('.HoverChild').not($not).hide();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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