我在编码方面相当熟练,但偶尔我也会遇到一些代码,它们似乎在做基本相同的事情。我的主要问题是,为什么你要使用.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);
});

当前回答

他们每个人都没有额外的优势。这完全取决于你的情况。下面的代码显示了它们的区别。

    Before inserts your html here
<div id="mainTabsDiv">
    Prepend inserts your html here
    <div id="homeTabDiv">
        <span>
            Home
        </span>
    </div>
    <div id="aboutUsTabDiv">
        <span>
            About Us
        </span>
    </div>
    <div id="contactUsTabDiv">
        <span>
            Contact Us
        </span>
    </div>
    Append inserts your html here
</div>
After inserts your html here

其他回答

把DOM (HTML页面)想象成一棵树。HTML元素是这个树的节点。

append()将一个新节点添加到您调用它的节点的子节点。

Example:$("#mydiv").append("<p>Hello there</p>") 

creates a child node <p> to <div>

after()将一个新节点作为同级或子节点添加到所调用节点的父节点。

Append()和prepend()用于在元素内部插入内容(使内容成为其子元素),而after()和before()用于在元素外部插入内容(使内容成为其兄弟元素)。

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() vs .after()

.append():将参数指定的内容插入到匹配元素集中每个元素的末尾。 .after():在匹配元素集的每个元素之后插入由参数指定的内容。

.prepend() vs .before()

prepend():将参数指定的内容插入到匹配元素集中每个元素的开头。 .before():在匹配元素集的每个元素之前插入由参数指定的内容。

append和prepend指的是对象的子对象而after和before指的是对象的兄弟对象。

试着回答你的主要问题:

为什么要使用.append()而不是.after(),反之亦然?

当你用jquery操作DOM时,你使用的方法取决于你想要的结果,一个经常使用的是替换内容。

在替换内容时,您需要.remove()内容并将其替换为新内容。如果你使用.remove()现有的标签,然后尝试使用.append(),它不会工作,因为标签本身已经被删除,而如果你使用.after(),新的内容被添加到(现在被删除的)标签的“外面”,并且不受之前的.remove()的影响。