通过jQuery,我们可以创建新的元素,并将它添加到页面上去。
示例:
(1)添加新段落
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$(".one").click(function(){
$("<p>我是新段落。</p>").appendTo($("body"));
})
})
</script>
<style>
.one {
width: 200px;
font-size: 18px;
font-weight: 700;
background-color: rgba(62, 158, 24, 0.582);
}
</style>
</head>
<body>
<p class="one">我是一个段落。</p>
</body>
</html>
点击该段落,将创建新的段落,并添加到页面中,如图:
(2)创建新的列表项
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$(".pre").click(function(){
$("ul").append($("<li class='new'>列表项</li>"));
})
})
</script>
<style>
.pre {
font-size: 18px;
color: blue;
margin-bottom: 5px;
}
.new {
font-size: 18px;
color: green;
margin-bottom: 5px;
}
</style>
</head>
<body>
<ul>
<li class="pre">列表项</li>
</ul>
</body>
</html>
点击该列表项,将创建新的列表项并添加至ul元素的末尾处,如图: