107

我想在每次单击按钮时使用 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> 
4

8 回答 8

179

试试这个$.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" />

于 2010-12-24T19:02:17.990 回答
21

扩展@vabhatia 所说的内容,这就是您在本机 JavaScript(没有 JQuery)中想要的。

ParentNode.insertBefore(<your element>, ParentNode.firstChild);

于 2015-06-16T08:48:27.520 回答
7

使用:$("<p>Test</p>").prependTo(".inner"); 查看jquery.com 上的 .prepend 文档

于 2014-02-12T09:47:27.470 回答
6
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).

于 2014-05-14T04:36:46.060 回答
2
parentElement.prepend(newFirstChild);

这是(可能)ES7 中的新增功能。它现在是 vanilla JS,可能是由于 jQuery 的流行。它目前在 Chrome、FF 和 Opera 中可用。转译器应该能够处理它,直到它在任何地方都可用。

PS你可以直接前置字符串

parentElement.prepend('This text!');

链接:developer.mozilla.org - Polyfill

于 2017-05-08T00:26:01.197 回答
0

此处必填

<div class="outer">Outer Text <div class="inner"> Inner Text</div> </div>

添加者

$(document).ready(function(){ $('.inner').prepend('<div class="middle">New Text Middle</div>'); });

于 2015-08-05T07:57:38.160 回答
-1
$('.parent-div').children(':first').before("<div class='child-div'>some text</div>");
于 2014-03-14T09:50:11.457 回答
-1

$(".child-div div:first").before("Your div code or some text");

于 2014-03-11T11:51:00.343 回答