我正在努力将元素移至DOM中的下一个元素。我可以移动它,但它会不断将自身重复到同一个类的其他div中。
这是我的HTML:
<p>The first text that needs to be moved</p>
<div class="tmb">
<span class="price">500</span>
</div>
<p>Second text that needs to be moved</p>
<div class="tmb">
<span class="price">500</span>
</div>
我想发生的是,第一个p
元素将在第一个.price
元素之后插入。第二个p
元素将插入在第二个.price
元素之后。我不能给p
元素一个类,因为它们是动态创建的。
我有这个jQuery的:
$(".tmb").prev("p").insertAfter("span.price");
但这会在逻辑上将元素移动到p
每个元素之后.price
。我只希望它.price
在DOM中遇到的第一个元素之后移动。
为此,您可以遍历所有p
元素,因为它们存在多个,然后将appendTo()
其添加到相关元素中.tmb
。尝试这个:
$('p').each((i, p) => $(p).appendTo($(p).next('.tmb')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>The first text that needs to be moved</p>
<div class="tmb">
<span class="price">500</span>
</div>
<p>Second text that needs to be moved</p>
<div class="tmb">
<span class="price">500</span>
</div>
或者,您可以遍历所有.tmb
以a开头p
和insertAfter()
其中.price
包含的元素。
$('p + .tmb').each((i, t) => $(t).prev('p').insertAfter($(t).find('.price')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>The first text that needs to be moved</p>
<div class="tmb">
<span class="price">500</span>
</div>
<p>Second text that needs to be moved</p>
<div class="tmb">
<span class="price">500</span>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句