Jquery显示或隐藏子项链接(如果可用)

时间:2017-01-13 19:52:19

标签: javascript jquery

我对Jquery有疑问。如果我点击没有任何ul.children的Link1并且将添加类current_page_item(此代码中未显示,因为它将由Wordpress自动添加),则应隐藏Link2中的ul.children

如果我点击链接2,这将同时包含page_item_has_children current_page_item类,在这种情况下应显示ul.children。我已经尝试过我的代码,我知道这绝对是错误的。请给我你的意见。非常感谢。



if($(.navigation).hasClass(page_item_has_children)){
  (.navigation .page_item_has_children .children).hide();
}else if( $(.navigation).hasClass(page_item_has_children) && $(.navigation).hasClass(current_page_item)){
  (.navigation .page_item_has_children .children).show();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="navigation">
<li><a href="#">Link1</a></li>
<li class="page_item_has_children current_page_item"><a href="#">Link2</a>
  <ul class="children">
	<li class="page_item"><a href="#">Link3</a></li>
	<li class="page_item "><a href="#">Link4</a></li>
  </ul>
</li>
</ul>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

如何简单地隐藏所有嵌套的UL元素,然后只显示所单击的元素的子元素?

$(".navigation li").each(function() {
  // When we first load, hide all nested menus.
    $(this).children("ul").hide();
  if (localStorage.menuNumber) {
    $(".navigation li").eq(localStorage.menuNumber).children().show();
    }
  })
  .on("click", function() {
  // When any top-level ul is clicked, hide the
  //  nested menus then show the current one.
    $(this).parent().children().find("ul").hide();
    $(this).children().show();
  // We also want to persist this selection,
  //  should the user refresh...
  localStorage.menuNumber = $(this).index;
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="navigation">
  <li><a href="#">Link1</a>
  </li>
  <li class="page_item_has_children current_page_item"><a href="#">Link2</a>
    <ul class="children">
      <li class="page_item"><a href="#">Link3</a>
      </li>
      <li class="page_item "><a href="#">Link4</a>
      </li>
    </ul>
  </li>
</ul>

编辑它,以便在最初加载时,隐藏所有嵌套的uls。希望这可以帮助!并再次编辑,将点击的菜单存储在本地存储中。可悲的是,出于安全原因,这在这里不起作用。将其视为小提琴:https://jsfiddle.net/snowMonkey/fnuvvLwb/

答案 1 :(得分:0)

此解决方案更适合您的场景(根据评论进行编辑):

&#13;
&#13;
$(".navigation li").on("click", function() {
  if ($(this).hasClass("page_item_has_children") && $(this).hasClass("current_page_item")) {
    $(".navigation .children").show();
  } else {
    $(".navigation .children").hide();
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navigation">
  <li><a href="#">Link1</a>
  </li>
  <li class="page_item_has_children current_page_item links"><a href="#">Link2</a>
    <ul class="children">
      <li class="page_item"><a href="#">Link3</a>
      </li>
      <li class="page_item "><a href="#">Link4</a>
      </li>
    </ul>
  </li>
</ul>
&#13;
&#13;
&#13;