jQuery:附加到父级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4679874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: appendTo parent
提问by curly_brackets
I can't seem to get the appendTo to work. What do I do wrong?
我似乎无法让 appendTo 工作。我做错了什么?
$('div:nth-child(2n) img').appendTo(parent);
Current markup:
当前标记:
<div class="container">
<img src="123.jpg" />
<p>Hey</p>
</div>
<div class="container">
<img src="123.jpg" />
<p>Hey</p>
</div>
I want this output:
我想要这个输出:
<div class="container">
<p>Hey</p>
<img src="123.jpg" />
</div>
<div class="container">
<p>Hey</p>
<img src="123.jpg" />
</div>
Please help me guys... I'm tearing my hair of every minute.. :-S
请帮帮我……我每一分钟都在撕裂我的头发……:-S
回答by James Wiseman
The following should suffice:
以下应该就足够了:
$("div>img").each(function(){
$(this).appendTo($(this).parent());
});
See it working here: http://jsfiddle.net/EtxqL/
看到它在这里工作:http: //jsfiddle.net/EtxqL/
You can't infer each item's parent from the 'selector' parameter to appendTo(). The only way to do what you want is to loop through the items, appending each one to its parent. Check out the APIs in the following link.
您无法从 appendTo() 的 'selector' 参数推断每个项目的父项。做你想做的唯一方法是遍历项目,将每个项目附加到其父项。查看以下链接中的 API。
回答by David Tang
Is this what you're after?
这是你追求的吗?
$('.container > img').each(function () {
$(this).parent().append(this);
});
It simply takes the <img>
within every container and moves as the first child of the container.
它只是简单地获取<img>
每个容器内的 并作为容器的第一个子项移动。
回答by Yoram de Langen
You can use .prepend()instead of append Append insert at the end off a the parent. But prepend insert at the begin from the parent. so then like:
您可以使用.prepend()而不是在父级的末尾追加追加插入。但是在从父级开始时预先插入。所以然后喜欢:
$('.container > p').each(function () {
$(parent).prepend(this);
});
回答by Simon
I made a little exampleand I hope you mean the same thing...
$(document).ready(function() {
$('.container > img').each(function() {
$(this).parent().append(this);
});
});