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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:30:52  来源:igfitidea点击:

How to append element after first child div in jquery?

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-childand after:

您可以使用:first-childand执行此操作after

$("#mydiv div:first-child").after(newDiv);

Demo

演示

回答by Control Freak

I prefer using eq()instead of first-childbecause 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 0value in the eq(0)function to eq(1)or eq(2).

我更喜欢使用eq()而不是first-child因为它更灵活,如果我想将它更改为第二个或第三个 div 之后,我可以0eq(0)函数中的值更改为eq(1)or eq(2)

 $("#mydiv div:eq(0)").after('<div>Place to Insert Subsequent div</div>')

http://jsfiddle.net/KjY7H/

http://jsfiddle.net/KjY7H/

回答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")');

http://jsfiddle.net/cadence96/tyBnX/1/

http://jsfiddle.net/cadence96/tyBnX/1/