我想在每次单击按钮时使用 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>Test</p>").prependTo(".inner");
查看jquery.com 上的 .prepend 文档
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of children. Equivalently, and more readably, use parentNode.appendChild(newChild).
parentElement.prepend(newFirstChild);
这是(可能)ES7 中的新增功能。它现在是 vanilla JS,可能是由于 jQuery 的流行。它目前在 Chrome、FF 和 Opera 中可用。转译器应该能够处理它,直到它在任何地方都可用。
PS你可以直接前置字符串
parentElement.prepend('This text!');
此处必填
<div class="outer">Outer Text
<div class="inner"> Inner Text</div>
</div>
添加者
$(document).ready(function(){
$('.inner').prepend('<div class="middle">New Text Middle</div>');
});
$('.parent-div').children(':first').before("<div class='child-div'>some text</div>");
$(".child-div div:first").before("Your div code or some text");