问题描述
我有一个这样的 HTML 代码:
<div class="foobar"></div>
我想在 div.foobar
元素之前附加 div#content
内的子元素.怎么能这样?
在我回答你的问题之前,让我让你更清楚、更容易地了解你想要什么
Append 表示可以在选择器的末尾插入元素作为子元素
示例 append() 和 appendTo()
Prepend 表示可以在选择器的开头插入元素作为子元素
示例 prepend() 和 prependTo()
请注意,选择器将被视为 parent
Before 表示您可以在选择器之前添加元素
示例 before() 和 insertBefore()
After 表示您可以在选择器之后添加元素
示例 after() 和 insertAfter()
before and after does not
将选择器视为 parent
元素
现在回答你的问题
你可以使用prepend or before
<div class="foobar"></div>$("your element").insertBefore("#content div.foobar")//或$("#content div.foobar").before("element")//或$("#content").prepend("element")//或$("元素").prependTo("#content")
注意prepend()和prependTo()
I have an HTML code like this:
<div id="content">
<div class="foobar"></div>
</div>
I want to append child elements inside div#content
before the div.foobar
element. How can do that?
Before I answer your question let me make something more clearer and easier to u so that you understand what your trying to
Append means you can insert elements as child elements at the end of the selector
example append() and appendTo()
Prepend means you can insert elements as child elements at the beginning of the selector
example prepend() and prependTo()
Notice that selector will be considered as a parent
Before means you can add elements just before the selector
example before() and insertBefore()
After means you can add elements just after the selector
example after() and insertAfter()
before and after does not
treat selector as a parent
element
Now to answer your question
You can do it using prepend or before
<div id="content">
<div class="foobar"></div>
</div>
$("your element").insertBefore("#content div.foobar") // or
$("#content div.foobar").before("element") // or
$("#content").prepend("element") // or
$("element").prependTo("#content")
Notice the selector positions in prepend() and prependTo()
这篇关于jQuery:在子元素之前附加子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!