append(content|fn)
概述
向每个匹配的元素内部追加内容,这个操作与对指定的元素执行appendChild方法,将它们添加到文档中的情况类似
参数
content 要追加到目标中的内容
function(index, html) 返回一个HTML字符串,用于追加到每一个匹配元素的里边。接受两个参数,index参数为对象在这个集合中的索引值,html参数为这个对象原先的html值
prepend(content)
概述
向每个匹配的元素内部前置内容,这是向所有匹配元素内部的开始处插入内容的最佳方式
参数
content 要插入到目标元素内部前端的内容
function(index, html) 返回一个HTML字符串,用于追加到每一个匹配元素的里边。接受两个参数,index参数为对象在这个集合中的索引值,html参数为这个对象原先的html值
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<script type="text/javascript" src="js/jquery-3.1.1.min.js" ></script>
<title></title>
<script>
$(document).ready(function() {
$("#btn").click(function() {
$("ol").append(function(index, html) {
return "<li style='color: #FF0000;'>后面追加文本</li>";
}); $("ol").prepend(function(index, html) {
return "<li style='color: #FF0000;'>前面追加文本</li>";
}); $("ol").append(appendcontext); $("ol").prepend(prependcontext); });
}); function appendcontext() {
return "<li style='color: #0000FF;'>后面追加文本</li>";
} function prependcontext() {
return "<li style='color: #0000FF;'>前面追加文本</li>";
}
</script>
</head> <body>
<ol>
<li>这是一个段落。</li>
<li>这是另外一个段落。</li>
</ol>
<button id="btn">添加文本</button>
</body> </html>
after(content|fn)
概述
在每个匹配的元素外部之后插入内容
参数
content 插入到每个目标后的内容
function 函数必须返回一个html字符串
before(content|fn)
概述
在每个匹配的元素外部之前插入内容
参数
content 插入到每个目标后的内容
function 函数必须返回一个html字符串
<!DOCTYliE html>
<html> <head>
<meta charset="UTF-8">
<script type="text/javascript" src="js/jquery-3.1.1.min.js" ></script>
<title></title>
<script>
$(document).ready(function() {
$("#btn").click(function() {
$("ol").after(function() {
return "<b style='color: #FF0000;'>后面追加文本</b>";
});
$("ol").before(function() {
return "<b style='color: #FF0000;'>前面追加文本</b>";
});
$("ol").after(aftercontext);
$("ol").before(beforecontext);
});
}); function aftercontext() {
return "<b style='color: #0000FF;'>后面追加文本</b>";
} function beforecontext() {
return "<b style='color: #0000FF;'>前面追加文本</b>";
}
</script>
</head> <body>
<ol>
<li>这是一个段落。</li>
<li>这是另外一个段落。</li>
</ol>
<button id="btn">添加文本</button>
</body> </html>