jQuery 如何在jquery中的第一个子div之后附加元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11354892/
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
How to append element after first child div in jquery?
提问by Rolando
Assuming I have the following divs:
假设我有以下 div:
<div id="mydiv">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
How can I in jquery or javascript make it such that I can append an element right after the first child of "mydiv". Or is there some selector to allow me to select and append after the first child?
我如何在 jquery 或 javascript 中使它能够在“mydiv”的第一个子元素之后立即附加一个元素。或者是否有一些选择器允许我在第一个孩子之后选择和附加?
<div>
<div>1</div>
<div>Place to Insert Subsequent div</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
回答by Tim Cooper
You can do this using :first-child
and after
:
您可以使用:first-child
and执行此操作after
:
$("#mydiv div:first-child").after(newDiv);
回答by Control Freak
I prefer using eq()
instead of first-child
because it's more flexible, in case I ever wanted to change it to be after the 2nd or 3rd div, i can just change the 0
value in the eq(0)
function to eq(1)
or eq(2)
.
我更喜欢使用eq()
而不是first-child
因为它更灵活,如果我想将它更改为第二个或第三个 div 之后,我可以0
将eq(0)
函数中的值更改为eq(1)
or eq(2)
。
$("#mydiv div:eq(0)").after('<div>Place to Insert Subsequent div</div>')
回答by Ricardo Casta?eda
To maintain readability you can store in a variable the div you want to append:
为了保持可读性,您可以将要附加的 div 存储在变量中:
var subsequentDiv = $('<div>Place to Insert Subsequent div</div>');
Then using your variable use your prefered jQuery method, in my example I'm using "insertAfter":
然后使用你的变量使用你喜欢的 jQuery 方法,在我的例子中我使用“insertAfter”:
subsequentDiv.insertAfter('#mydiv div:eq(0)'); // selects children by its index, the first div is equal to 0
subsequentDiv.insertAfter('#mydiv div:lt(1)'); // selects children that its index is lower than 1 (it means the second div)
A different way to achieve the same result, is by reading the content of the div with the "contains filter":
实现相同结果的另一种方法是使用“包含过滤器”读取 div 的内容:
subsequentDiv.insertAfter('#mydiv div:contains("1")');