如何使用 jQuery 在 div 中动态添加 div。它也应该先显示?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9308413/
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-27 10:38:02  来源:igfitidea点击:

How to add div dynamically inside a div using jQuery. It should display first also?

jqueryjquery-uidynamichtml

提问by DEVOPS

I have a parent div like this.

我有一个这样的父 div。

<div id='parent'>
   <div id='child_1'>........</div>
   <div id='child_2'>........</div>
   <div id='child_3'>........</div>
   <div id='child_4'>........</div>
</div>

I want to add one div like this:

我想像这样添加一个 div:

<div id='page_number'> You are watching 5th object out of 100 </div>

Inside parent div I'm using append to do like that.

在父 div 中,我使用 append 来做这样的事情。

$("#parent").append("<div id='page_number'> You are watching 5th object out of 100 </div>");

But its comming after child_4 th div. But I need to display it just below of child_1. It should come like this

但它是在 child_4 th div 之后到来的。但我需要将它显示在 child_1 的正下方。它应该是这样的

<div id='parent'>
   <div id='page_number'> You are watching 5th object out of 100 </div>
   <div id='child_1'>........</div>
   <div id='child_2'>........</div>
   <div id='child_3'>........</div>
   <div id='child_4'>........</div>
</div>

How can I do like this.

我怎么能这样。

回答by Pranay Rana

make use of jquery function .prepend(): Insert content, specified by the parameter, to the beginning of each element in the set of matched elements

利用jquery函数.prepend():将参数指定的内容插入到匹配元素集合中每个元素的开头

$('Selector ').prepend($('<div> new div </div>'));

回答by Hadas

use prepend instead of append:

使用前置而不是附加:

$("#parent").prepend("<div id='page_number'> You are watching 5th object out of 100 </div>");

回答by Frédéric Hamidi

Use prepend()instead of append():

使用prepend()而不是append()

$("#parent").prepend(
    "<div id='page_number'> You are watching 5th object out of 100 </div>");

回答by Abdullah Khan

See $("#parent").append("")adds your div at the end of the selected element.... if you want to add your divsas the first child of the parent, try prepend...

请参阅$("#parent").append("")在所选元素的末尾添加您的 div.... 如果您想将您divs的添加为父项的第一个子项,请尝试添加...

$("#parent").prepend("");

回答by Harag

As well as using the .prepend() command mentioned by the other answers you can also use the .prependTo()command:

除了使用其他答案提到的 .prepend() 命令之外,您还可以使用.prependTo()命令:

$("<div id='page_number'>You are watching 5th object out of 100 </div>").prependTo("#parent");

回答by Mario Corchero

You are looking for "prepend":

您正在寻找“前置”:

prepend Api

前置 Api

$("#parent").prepend(Your HTML)