新添加的div应该放在正文的顶部,旧的div应该放在新添加的div下
_________ | | | Newly | | added | | | |_________| _________ | | | second | | last | | added | |_________| _________ | | | third | | last | | added | |_________|
答案 0 :(得分:0)
你可以使用.prepend()
为尸体
查看下面的代码段
$(function(){
$('button').on('click',function(){
var count = $(this).data('button');
if(!count){
$('body').prepend('<div class=customdivs>DIV:'+1+'<div>');
$(this).data('button',1)
}else{
$('body').prepend('<div class=customdivs>DIV:'+(count+1)+'<div>');
$(this).data('button',count+1);
}
})
});
.customdivs{border:1px solid #ccc; width:60px;height:30px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button>Make Div</button>
</body>
答案 1 :(得分:0)
如果没有jQuery,你可以这样做:
HTML:
<div id="container">
</div>
<div id="div-creator">
Click me!
</div>
JS:
var button = document.querySelector('#div-creator');
var container = document.querySelector('#container');
var onClickButton = function() {
if(!this.count) this.count = 0;
this.count++;
var newDiv = document.createElement('div');
newDiv.innerHTML = "It's a me! " + this.count;
if(container.childElementCount === 0) {
container.appendChild(newDiv);
} else {
container.insertBefore(newDiv, container.childNodes[0]);
}
}
button.addEventListener('click', onClickButton);
演示:here