jquery - 如何将元素移动到 DOM 中的下一个父元素?
问题描述
我正在努力将一个元素移动到 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>
推荐阅读
- vba - PPT宏需要帮助
- rust - 过多的内存操作,我可以在整个链条中借用可变的吗?
- rabbitmq - RabbitMQ with pika:同一通道上不同队列的不同回调?
- python - 从数据帧的两列创建邻接矩阵而不循环 df
- html - 如何更改 django 中的默认文件上传按钮
- javascript - 如何在其他 onclick 内的函数 onclick 中使用 preventDefault
- javascript - 在所有多个嵌套的 ng-repeats 完成后如何调用函数?
- asynchronous - 单线程中的异步代码如何真正工作?
- python - 如何使用 groupby 列的索引制作 Pandas Dataframe 列中的所有元素?
- python - Docker Swarm 无法通过服务名称解析 DNS,Python Celery Workers 连接到 RabbitMQ 代理,导致连接超时