我有一个关于.wrapAll()
的问题。到目前为止我得到了这段代码:
<div id="firstDivContainer">
<div class="element">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
</div>
<div id="secondDivContainer">
<div class="element">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="element">stuff</div>
</div>
我想要另外一个包装第一套手风琴的div
。所以我尝试了:
if ($('#firstDivContainer').find('.accordion').length != 0) {
$(".accordion").wrapAll("<div id='accordionBox' />");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="firstDivContainer">
<div class="element">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
</div>
<div id="secondDivContainer">
<div class="element">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="element">stuff</div>
</div>
但是他从第二组中移除了手风琴并将它们添加到第一组。结果应该是:
<div id="firstDivContainer">
<div class="element">stuff</div>
<div id="accordionBox">
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
</div>
</div>
<div id="secondDivContainer">
<div class="element">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="element">stuff</div>
</div>
但相反,我得到了
<div id="firstDivContainer">
<div class="element">stuff</div>
<div id="accordionBox">
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
<div class="accordion">stuff</div>
</div>
</div>
<div id="secondDivContainer">
<div class="element">stuff</div>
<div class="element">stuff</div>
</div>
我想解决方案只是一个小小的改变,但我目前仍然坚持这个dratz。
只需缩小初始选择器,所以你只在.accordion
中选择#firstDivContainer
s:
$("#firstDivContainer .accordion").wrapAll("<div id='accordionBox' />");
$("#firstDivContainer .accordion").wrapAll("<div id='accordionBox' />");
应该这样做。