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

标签 javascript jquery

我有以下代码,我正在尝试阻止 if 两次触发 .hide(),目前使用的是 .not()。这两种情况是:

  • $(this).parent().closest(".HoverChild")
  • $(this).children(".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>

您在这方面的帮助将不胜感激。非常感谢。

格伦2223

最佳答案

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();

关于javascript - jQuery .NOT() $(this) 或 $(this).parent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28477362/

相关文章:

javascript - 用户拖动元素时更改元素的背景

javascript - Angular 2 ngModel不绑定(bind)类定义中定义的对象属性

jquery - 边界半径对改变类没有影响

javascript - 向现有的 JQuery 插件添加功能

javascript - 使用 Jquery Ajax Tomcat 的特殊字符的基本身份验证

javascript - Jquery show hide 没有按预期工作?

javascript - 选中复选框后不显示 JQuery Mobile Div

javascript - 无法以编程方式向图层添加要素

javascript - Angular 中的干净 URL

javascript - 在 Chrome(打包)应用程序之间共享实现文件?