使用jQuery的 append( ) 方法,我们可以在被选元素的结尾处插入指定的内容。
语法格式:
$(selector).append(content,function(index,currentHTML))
参数:
content(必需):插入的内容(可以是HTML元素)。
function(index,currentHTML)(可选):返回待插入内容的函数。
注意:
(1)index为元素的索引。
(2)currentHTML为被选元素的当前 HTML。
示例:
(1)常规方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="../jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").append("<p class = 'para'>一段文字。</p>");
})
})
</script>
<style>
div {
width: 150px;
height: 150px;
background-color: rgba(74, 165, 66, 0.404);
}
.para {
color: blue;
}
</style>
</head>
<body>
<button>按钮</button>
<div><p>我是一个盒子。</p></div>
</body>
</html>
点击按钮,DIV的结尾处将插入新段落,效果如图:
(2)函数方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="../jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("ol li").append(function(index,currentHTML){
return "<em>我的索引号为 " + index + " 我当前的HTML为" + currentHTML + "</em>";
})
})
})
</script>
</head>
<body>
<ol>
<li><b>我是列表项1。</b></li>
<li><b>我是列表项2。</b></li>
<li><b>我是列表项3。</b></li>
</ol>
<button>按钮</button>
</body>
</html>
点击按钮,效果如图: