使用NextUntil进行WrapAll

时间:2017-07-20 10:16:19

标签: javascript jquery

如何确保所有带.px-sub-menu-item的课程都包含在div中?

(function($) {
  $('.px-sub-menu-item').each(function() {
    $(this).nextUntil('.px-sub-menu-item').addBack('.px-sub-menu-item').wrapAll('<div class="px-menu-wrap"></div>');
  });
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <a href="#" class="px-main-menu-item">Home</a><br>
  <a href="#" class="px-sub-menu-item">Submenu 1</a><br>
  <a href="#" class="px-main-menu-item">Home 2</a><br>
  <a href="#" class="px-sub-menu-item">Submenu 2</a><br>
  <a href="#" class="px-sub-menu-item">Submenu 3</a><br>
  <a href="#" class="px-main-menu-item">Home 3</a><br>
</nav>

https://jsfiddle.net/kqzj1tex/

1 个答案:

答案 0 :(得分:1)

wrapAll将所有选择者包含在一个 div中。如果您希望将每个.px-sub-menu-item换行到单独的div中,则需要使用wrap函数。

&#13;
&#13;
$('.px-sub-menu-item').wrap('<div></div>');
&#13;
div > .px-sub-menu-item{
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>

<a href="#" class="px-main-menu-item">Home</a><br>
<a href="#" class="px-sub-menu-item">Submenu 1</a><br>
<a href="#" class="px-main-menu-item">Home 2</a><br>
<a href="#" class="px-sub-menu-item">Submenu 2</a><br>
<a href="#" class="px-sub-menu-item">Submenu 3</a><br>                      
<a href="#" class="px-main-menu-item">Home 3</a><br>

</nav>
&#13;
&#13;
&#13;