如何使用jQuery将元素插入DOM?
在某些情况下,您想在现有文档中插入一个或多个新DOM元素。jQuery提供了多种在不同位置插入元素的方法。
after(content)方法将内容插入每个匹配的元素之后,而before(content)方法将内容插入每个匹配的元素之前。
后内容
after(content)方法在每个匹配的元素之后插入内容。
示例
您可以尝试运行以下代码,以了解如何使用after()方法将元素插入DOM:
<html>
<head>
<title>jQuery after(content) method</title>
<script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).after('<div class = "div"></div>' );
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>内容前
before(content)方法在每个匹配的元素之前插入内容。
示例
您可以尝试运行以下代码,以了解如何使用before()方法将元素插入DOM:
现场演示
<html>
<head>
<title>jQuery before(content) method</title>
<script src = "https://cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).before('<div class = "div"></div>' );
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短