我在编码方面相当熟练,但偶尔我也会遇到一些代码,它们似乎在做基本相同的事情。我的主要问题是,为什么你要使用.append()而不是.after()或反之亦然?
我一直在寻找,但似乎无法找到两者之间的区别以及何时使用和何时不使用的明确定义。
一个比另一个有什么好处,为什么我要使用一个而不是另一个?有人能给我解释一下吗?
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);
});
See:
.append()将数据放在最后一个索引和元素中
.prepend()将前面的elem放在第一个索引
假设:
<div class='a'> //<---you want div c to append in this
<div class='b'>b</div>
</div>
当.append()执行时,它看起来像这样:
$('.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>
在执行时修改.append()。
当.prepend()执行时,它看起来像这样:
$('.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>
在执行时修改.prepend()。
.after()将元素放在元素的后面
.before()将元素放在元素之前
使用后:
$('.a').after($('.c'));
执行后:
<div class='a'>
<div class='b'>b</div>
</div>
<div class='c'>c</div> //<----this will be placed here
在执行时修改.after()。
使用前:
$('.a').before($('.c'));
执行后:
<div class='c'>c</div> //<----this will be placed here
<div class='a'>
<div class='b'>b</div>
</div>
在执行时摆弄.before()。
下面显示的这张图像可以清晰地理解和显示.append(), .prepend(), .after()和.before()之间的确切区别。
从图中可以看到.append()和.prepend()将新元素作为子元素(棕色)添加到目标。
.after()和.before()将新元素作为兄弟元素(黑色)添加到目标中。
为了更好地理解,这里有一个演示。
编辑:这些函数的翻转版本:
使用以下代码:
var $target = $('.target');
$target.append('<div class="child">1. append</div>');
$target.prepend('<div class="child">2. prepend</div>');
$target.before('<div class="sibling">3. before</div>');
$target.after('<div class="sibling">4. after</div>');
$('<div class="child flipped">or appendTo</div>').appendTo($target);
$('<div class="child flipped">or prependTo</div>').prependTo($target);
$('<div class="sibling flipped">or insertBefore</div>').insertBefore($target);
$('<div class="sibling flipped">or insertAfter</div>').insertAfter($target);
在这个目标上:
<div class="target">
This is the target div to which new elements are associated using jQuery
</div>
因此,尽管这些函数颠倒了形参顺序,但每个函数都创建了相同的元素嵌套:
var $div = $('<div>').append($('<img>'));
var $img = $('<img>').appendTo($('<div>'))
...但是它们返回一个不同的元素。这对方法链接很重要。