我对编码相当精通,但有时我会遇到代码似乎基本上做了同样的事情。这里我的主要问题是,为什么要使用.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);
});发布于 2013-02-13 12:58:44
请参见:
.append()将数据放在last index的元素中,并
.prepend()将前置元素放在first index
假设:
<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>Fiddle with .append() in execution.
当.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>Fiddle with .prepend() in execution.
.after()将元素放在元素之后
.before()将元素放在元素之前
在以下情况下使用:
$('.a').after($('.c'));执行后:
<div class='a'>
<div class='b'>b</div>
</div>
<div class='c'>c</div> //<----this will be placed hereFiddle with .after() in execution.
使用之前:
$('.a').before($('.c'));执行后:
<div class='c'>c</div> //<----this will be placed here
<div class='a'>
<div class='b'>b</div>
</div>Fiddle with .before() in execution.
发布于 2014-12-21 20:58:00
下面显示的图像清晰地显示了.append()、.prepend()、.after()和.before()之间的区别

您可以从图像中看到,.append()和.prepend()将新元素作为子元素(棕色)添加到目标。
.after()和.before()将新元素作为兄弟元素(黑色)添加到目标。
为了更好地理解,这里有一个。
编辑:这些函数的翻转版本:

使用this code
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>'))...but它们返回一个不同的元素。这对method chaining来说很重要。
发布于 2013-02-13 12:54:44
append() & prepend()用于在元素内插入内容(使内容成为其子元素),而after() & before()用于在元素外插入内容(使内容成为其兄弟项)。
https://stackoverflow.com/questions/14846506
复制相似问题