在 jQuery 中,添加元素的操作主要用于在文档中追加内容。我们可以使用以下列出的几种方法来添加内容:
- append(): 在所选元素的末尾插入内容。
- prepend(): 在所选元素的开头插入内容。
- after(): 在所选元素的外部之后插入内容。
- before(): 在所选元素的外部之前插入内容。
使用 append() 方法
jQuery 中的 append() 方法用于在选中元素的末尾添加新元素。
语法:
$(selector).append("element_to_be_inserted")
参数: 此方法接受单个参数,即需要插入的元素。
返回值: 该方法不返回任何值。
示例: 这个例子使用了 append() 方法来添加新的列表项。
Append Elements
$(document).ready( function() {
$("#add_li").click( function() {
$("ol").append("")
})
})
输出:
使用 prepend() 方法
jQuery 中的 prepend() 方法用于在选中元素的开头(即内部内容的第一个位置)添加新元素。
语法:
$(selector).prepend("element_to_be_inserted")
参数: 此方法接受单个参数,即需要插入 DOM 的元素。
返回值: 该方法不返回任何值。
示例: 这个例子使用了 prepend() 方法来添加新的段落。
prepend() method
The first paragraph
The second paragraph
The third paragraph
$(document).ready( function() {
$("#add_p").click( function() {
$("#container").prepend("prepended paragraph
")
})
})
Prepend
输出:
使用 after() 方法
jQuery 中的 after() 方法用于在选中元素之后(作为兄弟节点)插入内容。
语法:
$(selector).after("element_to_be_inserted")
参数: 此方法接受单个参数,即需要插入 DOM 的内容。
返回值: 该方法不返回任何值。
示例: 这个例子使用了 after() 方法在图片后添加文本。
Add Elements using after() method

$(document).ready( function() {
$("#btn1").click(function() {
$("img").after("After");
});
})
输出:
使用 before() 方法
jQuery 中的 before() 方法用于在选中元素之前(作为兄弟节点)插入内容。
语法:
$(selector).before("element_to_be_inserted")
参数: 此方法接受单个参数,即需要插入 DOM 的内容。
返回值: 该方法不返回任何值。
示例: 这个例子使用了 before() 方法在图片前添加元素。
Add Element using before() method
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1