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

时间:2015-02-12 12:21:37

标签: javascript jquery

我有以下代码,我试图阻止两次点击.hide(),目前正在使用.not()。这两个场合是:

  • $(本).parent()。最近的( “HoverChild”)
  • $(本)。儿童( “HoverChild”)

编辑:因为它没有使用第二个$(this),所以它隐藏了子元素,然后再次显示它。

$(".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>

非常感谢您对此的帮助。非常感谢。

glenn2223

1 个答案:

答案 0 :(得分:3)

not()只接受一个参数。您有三种选择可以达到您想要的效果。第一个是将数组传递给not()函数,如下所示:

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

或者,您需要在评估not()函数的第一个参数后过滤结果。您可以通过将另一个not()函数链接到过滤器来执行此操作,例如:

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

或者您可以使用add()$(this).parent().closest('.HoverChild')$(this)合并到一个jQuery集合中,然后评估not()

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