要使用jQuery将元素作为第一个子元素插入,请使用prepend()方法。prepend(content)方法会将content附加到每个匹配元素的内部。
您可以尝试运行以下代码,以了解如何使用jQuery作为第一个孩子插入元素:
<html>
<head>
<title>jQuery Example</title>
<script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
var x = 0;
$(document).ready(function() {
$('.add').on('click', function (event) {
var html = "<div class='child-div'>demo text " + x++ + "</div>";
$("#parent-div").prepend(html);
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #F38B00;
width:60px;
}
</style>
</head>
<body>
<div id="parent-div">
<div>Hello World</div>
</div>
<input type="button" value="点击添加" class="add" />
</body>
</html>