我想在每次单击按钮时使用jQuery将一个div作为第一个元素添加。
<div id='parent-div'>
<!--insert element as a first child here ...-->
<div class='child-div'>some text</div>
<div class='child-div'>some text</div>
<div class='child-div'>some text</div>
</div>
我想在每次单击按钮时使用jQuery将一个div作为第一个元素添加。
<div id='parent-div'>
<!--insert element as a first child here ...-->
<div class='child-div'>some text</div>
<div class='child-div'>some text</div>
<div class='child-div'>some text</div>
</div>
尝试使用$.prepend()
函数。
$("#parent-div").prepend("<div class='child-div'>some text</div>");
var i = 0;
$(document).ready(function () {
$('.add').on('click', function (event) {
var html = "<div class='child-div'>some text " + i++ + "</div>";
$("#parent-div").prepend(html);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent-div">
<div>Hello World</div>
</div>
<input type="button" value="add" class="add" />
扩展 @vabhatia 的说法,这是你想要的本机JavaScript代码(不使用JQuery)。
ParentNode.insertBefore(<your element>, ParentNode.firstChild);
使用方法:$("<p>测试</p>").prependTo(".inner");
请查看jquery.com上的.prepend文档
parentNode.insertBefore(newChild, refChild)
将新节点newChild作为parentNode的子节点,在现有的子节点refChild之前插入。(返回newChild)
如果refChild为空,newChild将添加到子节点列表的末尾。同样地,更易读的方式是使用parentNode.appendChild (newChild)。
parentElement.prepend(newFirstChild);
这是(可能)ES7中的新功能。由于jQuery的普及,它现在是原生JS。目前在Chrome、FF和Opera中可用。转换器应该能够处理它,直到它在所有地方都可用。
P.S. 您可以直接在字符串前面添加
parentElement.prepend('This text!');
Links: developer.mozilla.org - Polyfill
$('.parent-div').children(':first').before("<div class='child-div'>some text</div>");
这里是必需的
<div class="outer">外部文本
<div class="inner"> 内部文本</div>
</div>
添加者
$(document).ready(function(){
$('.inner').prepend('<div class="middle">新的中间文本</div>');
});
$(".child-div div:first").before("你的div代码或一些文本");