jQuery .append() 什么时候像 .insertBefore() 最后一个子子项与记录的 .insertBe

When does jQuery .append() act like .insertBefore() last child vs. as documented?

本文关键字:记录 insertBe insertBefore append 什么时候 jQuery 最后一个      更新时间:2023-09-26

http://jsfiddle.net/foaje732/2/网页来源:

<p id="words">Words
    <p>
        <label>Q1
            <input type="text" id="q1" name="myinput" />
        </label>
    </p>
</p>

Jscript:

$('#words').append($('<p></p>').html("This is clearly in the wrong place."));

您实际得到的:

的话。这显然是在错误的地方。Q1 [输入字段] 

这是因为您的标记是错误的,p元素不能包含另一个块元素,它只能包含内联元素。因此,您的标记在浏览器中呈现的实际 html 如下所示,这使您的输出正确。

<p id="words">Words</p>
<p>
    <label>Q1
        <input type="text" id="q1" name="myinput">
    </label>
</p>
<p></p>

因此,您可以寻找的一种可能的解决方案是使用div作为外部容器,例如

$('#words').append($('<p></p>').html("This is clearly in the wrong place."));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="words">Words
  <div>
    <label>Q1
      <input type="text" id="q1" name="myinput" />
    </label>
  </div>
</div>

我们无法在元素内获取任何子<element> p$('#words').children()将返回 0,以便它将您的代码appendp的顶部(在单词 -text 之后,而不是任何元素)。在这种情况下,如果要修复它,请尝试将p更改为div

<div id="words">
    <p>Words</p>
    <p>
        <label>Q1
            <input type="text" id="q1" name="myinput" />
        </label>
    </p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
$(document).ready(function(){
   $('#words').append($('<p></p>').html("This is clearly in the wrong place."));
})