jQuery append()和appendTo()方法都执行相同的任务,在匹配元素的内容之后添加文本或html内容。 主要区别在于语法。
例如,
<div class="box">I'm a big box</div>
<div class="box">I'm a big box 2</div>
1. $('selector')。append('new text');
$('.box').append("<div class='newbox'>I'm new box by prepend</div>");
2. $('new text')。appendTo('selector');
$("<div class='newbox'>I'm new box by appendTo</div>").appendTo('.box');
结果
上面的两个方法都执行相同的任务,但是使用不同的语法, append()或appendTo()之后的新内容将变为
<div class="box">
I'm a big box
<div class='newbox'>I'm new box by prepend</div>
</div>
<div class="box">
I'm a big box 2
<div class='newbox'>I'm new box by prepend</div>
</div>
自己尝试
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
.box{
padding:8px;
border:1px solid blue;
margin-bottom:8px;
width:300px;
height:100px;
}
.newbox{
padding:8px;
border:1px solid red;
margin-bottom:8px;
width:200px;
height:50px;
}
</style>
</head>
<body>
<h1>jQuery append() and appendTo example</h1>
<div class="box">I'm a big box</div>
<div class="box">I'm a big box 2</div>
<p>
<button id="append">append()</button>
<button id="appendTo">appendTo()</button>
<button id="reset">reset</button>
</p>
<script type="text/javascript">
$("#append").click(function () {
$('.box').append("<div class='newbox'>I'm new box by append</div>");
});
$("#appendTo").click(function () {
$("<div class='newbox'>I'm new box by appendTo</div>").appendTo('.box');
});
$("#reset").click(function () {
location.reload();
});
</script>
</body>
</html>
翻译自: https://mkyong.com/jquery/jquery-append-and-appendto-example/