我对.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>
&#13;
我希望另一个div
包装第一组手风琴。所以我尝试了:
if ($('#firstDivContainer').find('.accordion').length != 0) {
$(".accordion").wrapAll("<div id='accordionBox' />");
}
&#13;
<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>
&#13;
但是他从第二组中移除了手风琴并将它们添加到第一组。 结果应该是:
<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>
&#13;
但我得到了
<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>
&#13;
我想解决方案只是一个小小的改变,但我目前仍然坚持使用这个dratz。
答案 0 :(得分:3)
只需缩小初始选择器,因此您只在.accordion
内选择#firstDivContainer
:
$("#firstDivContainer .accordion").wrapAll("<div id='accordionBox' />");
答案 1 :(得分:1)
$("#firstDivContainer .accordion").wrapAll("<div id='accordionBox' />");
应该这样做。