私はコーディングにかなり精通していますが、時々、基本的に同じことをしているようなコードに出会います。ここでの一番の疑問は、なぜ.append()
ではなく.after()
を使うのか、あるいはその逆なのかということです。
探してみたのですが、この2つの違いや、いつ使用して、いつ使用しないのかについての明確な定義を見つけることができませんでした。
また、どちらかを使うメリットは何か、なぜどちらかを使う必要があるのでしょうか?誰か説明してくれませんか?
var txt = $('#' + id + ' span:first').html();
$('#' + id + ' a.append').live('click', function (e) {
e.preventDefault();
$('#' + id + ' .innerDiv').append(txt);
});
$('#' + id + ' a.prepend').live('click', function (e) {
e.preventDefault();
$('#' + id + ' .innerDiv').prepend(txt);
});
$('#' + id + ' a.after').live('click', function (e) {
e.preventDefault();
$('#' + id + ' .innerDiv').after(txt);
});
$('#' + id + ' a.before').live('click', function (e) {
e.preventDefault();
$('#' + id + ' .innerDiv').before(txt);
});
.append()は
last indexにある要素の中にデータを入れます。 .prepend()
は、前置する要素を first index
に配置します。
<div class='a'> //<---you want div c to append in this
<div class='b'>b</div>
</div>
$('.a').append($('.c'));
実行後に
<div class='a'> //<---you want div c to append in this
<div class='b'>b</div>
<div class='c'>c</div>
</div>
$('.a').prepend($('.c'));
が実行されると
<div class='a'> //<---you want div c to append in this
<div class='c'>c</div>
<div class='b'>b</div>
</div>
.after()は、要素を要素の後ろに置きます。 .before()
は、要素を要素の前に置きます。
$('.a').after($('.c'));
の実行後。
<div class='a'>
<div class='b'>b</div>
</div>
<div class='c'>c</div> //<----this will be placed here
$('.a').before($('.c'));
実行後
<div class='c'>c</div> //<----this will be placed here
<div class='a'>
<div class='b'>b</div>
</div>