Javascript 使用jquery重新定位html中的元素
我不知道如何以最佳方式实现这一点: 假设我有:Javascript 使用jquery重新定位html中的元素,javascript,jquery,html,Javascript,Jquery,Html,我不知道如何以最佳方式实现这一点: 假设我有: 使用 after()将帮助您将元素定位在所选元素之后 $(".parent").each(function(){ $(this).after($(".child", this)); }); JSFiddle: 注意:$(“.child”,this)只是$(this)的一个较短版本。查找(“.child”) 排除元素可以使用.not()或:not()或过滤器: e、 g.使用.not() 或使用:非伪选择器 $(".parent:not
使用
after()
将帮助您将元素定位在所选元素之后
$(".parent").each(function(){
$(this).after($(".child", this));
});
JSFiddle:
注意:$(“.child”,this)
只是$(this)的一个较短版本。查找(“.child”)
排除元素可以使用.not()
或:not()
或过滤器:
e、 g.使用.not()
或使用:非
伪选择器
$(".parent:not([data-anchor=2],[data-anchor=3])").each(function(){
$(this).after($(".child", this));
});
或者使用过滤器()
函数
$(".parent").filter(function(){
return $(this).data('anchor') == "2" || $(this).data('anchor') == "3";
}).each(function(){
$(this).after($(".child", this));
});
您可以通过在
.child
元素上循环并使用insertAfter()
将它们放置在最接近的父元素之后来实现这一点。父元素
元素:
$('.parent .child').each(function() {
$(this).insertAfter($(this).closest('.parent'));
});
您可以使用.after(fn)
方法,将函数作为参数返回所需的行为,它的一个好处是不显式使用循环,这样它将在内部为您执行此操作:
$('.parent')。在(function()之后{
返回$('child',this);
});代码>
.parent{边框:纯红3px;}
.child{边框:实心3px绿色;边距:3px 0;}
小孩
父母亲
小孩
父母亲
小孩
父母亲
您可以使用分离
方法这样做:
$(".parent").each(function() {
$(this).after($(this).find(".child").detach());
});
您可以通过检查年龄的元素来检查结构:)您好,谢谢!我喜欢这个解决方案!你能帮我个忙吗:我怎样才能排除那些具有某些属性的父母呢?例如,我需要排除那些数据锚=2和数据锚=3的,我不知道怎么做。老兄,你是最好的!“不是”的东西很漂亮!我不知道。分离在这里没有效果,因为after
将移动DOM中的元素。@TrueBlueAussie但是after
不应该只插入给定的元素而不首先从DOM中删除它吗oNo,它不会克隆单个元素(仅当需要多个元素时)。无论哪种方式,最终结果都是一样的,原始的被删除,因此这里不需要分离:这里的PSimple示例:如果没有删除,您将有4个:)
$('.parent .child').each(function() {
$(this).insertAfter($(this).closest('.parent'));
});
$(".parent").each(function() {
$(this).after($(this).find(".child").detach());
});