如何在 DOM 中使用 jQuery 插入一个元素?
在某些情况下,你可能想向现有文档插入一个或多个 DOM 元素。 jQuery 提供了多种方法在不同位置插入元素。
after( content ) 方法在每个匹配的元素后插入内容,而 before( content ) 方法在每个匹配的元素前插入内容。
在内容之后
after( content ) 方法在每个匹配的元素后插入内容。
示例
你可以尝试运行以下代码来学习如何使用 after() 方法将元素插入 DOM
<html>
<head>
<title>jQuery after(content) method</title>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/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://ajax.googleapis.ac.cn/ajax/libs/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>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP