如何使用 jQuery 在子節點中插入元素?
要使用 jQuery 在子節點中插入元素,請使用 prepend() 方法。prepend( content ) 方法向每個匹配元素的內部新增內容。
示例
您可以嘗試執行以下程式碼,瞭解如何使用 jQuery 在子節點中插入元素
<html>
<head>
<title>jQuery Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/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="Click to add" class="add" />
</body>
</html>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
JavaScript
PHP