如何使用带有click函数的jquery添加的伪元素

时间:2019-03-11 16:39:29

标签: jquery css3 accordion pseudo-element submenu

我输入的代码可以工作,但是我想使用以前创建的箭头类,而不是以这种方式li.parent使用$('.Arrow').click(function ()...,但是它对我不起作用,可以实现吗?

$('ul#nav li.parent').before('<a class="arrow" href="#"></a>');

$(document).ready(function() {
  $('.parent').click(function() {
    $('.parent').not(this).find('.sub-nav.visible').removeClass('visible');
    $('.sub-nav', this).toggleClass('visible'); //find .sub-nav of clicked .parent
  });
});
#nav ul.sub-nav {
  display: none;
}

#nav ul.visible {
  display: block;
}

.arrow {
  width: 10px;
  height: 10px;
  background: red;
  display: inline-block;
  float: right;
  position: relative;
  right: 50%;
  margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="nav">
  <li class="parent">Home
    <ul class="sub-nav">
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
    </ul>
  </li>
  <li class="parent">About
    <ul class="sub-nav">
      <li>First</li>
      <li>Second</li>
      <li>Third</li>
    </ul>
  </li>
  <li class="parent">Contact</li>
</ul>

1 个答案:

答案 0 :(得分:0)

$('.sub-nav').before('<a class="arrow" href="#"></a>');

$(document).ready(function() {
  $('.arrow').click(function() {
    var list = $(this).parent()
    var subList = $(list).children('.sub-nav')
    if(!$(subList).hasClass('visible')) {
    	$('.parent').not(this).find('.sub-nav.visible').removeClass('visible');
    }
    $(subList).toggleClass('visible');
  });
});
#nav ul.sub-nav {
  display: none;
}
#nav ul.visible {
  display: block;
}
.arrow {
  width: 10px;
  height: 10px;
  background: red;
  display: inline-block;
  float: right;
  position: relative;
  right: 50%;
  margin-top: 5px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="nav">
  <li class="parent">Home
    <ul class="sub-nav">
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
    </ul>
  </li>
  <li class="parent">About
    <ul class="sub-nav">
      <li>First</li>
      <li>Second</li>
      <li>Third</li>
    </ul>
  </li>
  <li class="parent">Contact</li>
  <li class="parent">Help
    <ul class="sub-nav">
      <li>First</li>
      <li>Second</li>
      <li>Third</li>
    </ul>
  </li>
  <li class="parent">Argon
    <ul class="sub-nav">
      <li>First</li>
      <li>Second</li>
      <li>Third</li>
    </ul>
  </li>
</ul>

稍微整理一下代码库,但这应该可以为您提供所需的东西。

编辑

在JS文件中添加了if语句,该语句将处理重复单击列表的操作,以切换列表。