jQuery append()方法
jQuery中的append()方法是用来在所选元素的末端插入一些内容。
语法:
$(selector).append( content, function(index, html) )
参数:该方法接受上面提到的和下面描述的两个参数。
- content。这是一个必要的参数,用于指定要插入到所选元素末尾的内容。内容的可能值是HTML元素,jQuery对象,和DOM元素。
- function(index, html)。这是一个可选的参数,用于指定返回要插入的内容的函数。
- index。它用于返回元素的索引位置。
- html。它用于返回所选元素的当前HTML。
例子1:这个例子将内容附加在段落和列表的最后。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery append() Method
</title>
<script src="
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Script to append content -->
<script>
(document).ready(function () {
("#btn1").click(function () {
("p").append(" <b>Append Geeks</b>.");
});
("#btn2").click(function () {
$("ol").append("<li>Append Gfg</li>");
});
});
</script>
</head>
<body>
<h1 style="margin-left: 150px;">Geeks</h1>
<p>GeeksforGeeks</p>
<p>Jquery</p>
<ol>
<li>Gfg 1</li>
<li>Gfg 2</li>
<li>Gfg 3</li>
</ol>
<button id="btn1">Append Geeks</button>
<button id="btn2">Append Gfg</button>
</body>
</html>
输出:
例子2:这个例子将内容附加在段落的末尾。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery append() Method
</title>
<script src="
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Script to append content -->
<script>
(document).ready(function () {
("button").click(function () {
$("p").append(function (n) {
return "<b> Index of Element is "
+ n + ".</b>";
});
});
});
</script>
</head>
<body>
<h1 style="margin-left:150px;">Geeks</h1>
<p>Geeks for Geeks</p>
<p>Jquery_append</p>
<button>
Insertion using Append Method()
</button>
</body>
</html>
输出: