我有示例页面
<div class = "tistimonials">
<div class = "testimonail-common">
<div class = "testimonial-content">
<div class = "testimonial-content__special"></div>
</div>
<div class = "testimonial-content2">
<div class = "tistimonial-wrapper">
<div class = "testimonial-example">example1</div>
</div>
</div>
</div>
<div class = "testimonail-common">
<div class = "testimonial-content">
<div class = "testimonial-content__special"></div>
</div>
<div class = "testimonial-content2">
<div class = "tistimonial-wrapper">
<div class = "testimonial-example">example2</div>
</div>
</div>
</div>
</div>
我需要将类 .testimonial-example 的 div 移动到最近的类 .testimonial-content__special 的 div 中,所以我需要将每个 .testimonial-example 移动到 .testimonial-content__special,但它们应该在它们的 .testimonail- 中普通 div,不是所有的 .testimonial-example 都在第一个 .testimonial-content__special 中。
我试过了
$('.testimonial-example').appendTo($(".testimonial-content__special"));
还有这个
$('.testimonial-example').appendTo(.closest($(".testimonial-content__special")));
也许我弄错了或者只是错误的代码,我不知道,有人可以帮助我吗?
最佳答案
如果您尝试对每个元素执行此操作,请使用 .each 循环。然后,您将可以使用 $(this) 访问当前元素。然后您可以将该元素附加到您选择的元素。
$('.testimonial-example').each(function() {
// get the target element.
// .closest() only checks anchestors but not the anchestors children.
var target = $(this).closest('.testimonail-common').find('.testimonial-content__special');
target.append($(this));
});
嗯,乔尔
关于javascript - 改变元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252108/