jQueryのappend()とappendTo()の例
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( ‘セレクタ’);
$("<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>