prepend()

将参数内容插入到每个匹配元素的前面(元素内部)。

.prepend ( content [, content ])
  • content 类型: String, Element, jQuery 。DOM元素,元素数组,HTML字符串,或者jQuery对象,将被插入到匹配元素前的内容。
  • content 类型: String, Element, jQuery 。一个或多个DOM元素,元素数组,HTML字符串,或者jQuery对象,将被插入到匹配元素前的内容。
.prepend ( function ( index, html ))

function ( index, html ) 类型:Function() 。一个返回HTML字符串,DOM元素,jQuery对象的函数,该字符串用来插入到匹配元素的开始处。接收index 参数表示元素在匹配集合中的索引位置和html 参数表示元素上原来的 HTML 内容。在函数中 this 指向元素集合中的当前元素。

.prepend(content)

.prepend() 方法将指定元素插入到匹配元素里面作为它的第一个子元素(如果要作为最后一个子元素插入用 .append() )。

.prepend() .prependTo() 实现同样的功能,主要的不同是语法,插入的内容和目标的位置不同。对于 .prepend() 而言,选择器表达式写在方法的前面,作为待插入内容的容器,将要被插入的内容作为方法的参数。而 .prependTo() 正好相反,将要被插入的内容写在方法的前面,可以是选择器表达式或动态创建的标记,待插入内容的容器作为参数。

请看下面的HTML:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

我们可以创建内容然后同时插入到好几个元素里面:

$('.inner').prepend('<p>Test</p>');

每个 <div> 元素得到新内容:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">
    <p>Test</p>
    Hello
  </div>
  <div class="inner">
    <p>Test</p>
    Goodbye
  </div>
</div>

我们也可以在页面上选择一个元素然后插在另一个元素里面:

$('.container').prepend($('h2'));

如果一个被选中的元素被插入到另外一个地方,这是移动而不是复制:

<div class="container">
    <h2>Greetings</h2>
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>
</div>

重要 :如果有多个目标元素,内容将被复制然后插入到每个目标里面。

Additional Arguments(额外的参数)

类似的其他内容的添加方法,如 .append() .before() , .prepend() 还支持传递输入多个参数。支持的输入包括DOM元素,jQuery对象,HTML字符串,DOM元素的数组。

例如,下面将插入两个新的 <div> 和现有的 <div> 到 body作为最后三个子节点:

var $newdiv1 = $('<div id="object1"/>'),
    newdiv2 = document.createElement('div'),
    existingdiv1 = document.getElementById('foo');
 
$('body').prepend($newdiv1, [newdiv2, existingdiv1]);

.prepend() 可以接受任何数量的额外的参数,相同的结果,可以通过传入三个 <div> 为三个独立的参数实现,就像这样 $('body').prepend($newdiv1, newdiv2, existingdiv1) 。参数的类型和数量将在很大程度上取决于在代码中被收集的元素。

例子

Prepends some HTML to all paragraphs.

<!DOCTYPE html>
<html>
<head>
  <style>p { background:yellow; }</style>
  <script src="./static/js/jquery-3.5.0.js"></script>
</head>
<body>
  <p>there, friend!</p>
 
<p>amigo!</p>
<script>$("p").prepend("<b>Hello </b>");</script>
 
</body>
</html>

Prepends a DOM Element to all paragraphs.

<!DOCTYPE html>
<html>
<head>
  <style>p { background:yellow; }</style>
  <script src="./static/js/jquery-3.5.0.js"></script>
</head>
<body>
  <p>is what I'd say</p>
<p>is what I said</p>
<script>$("p").prepend(document.createTextNode("Hello "));</script>
 
</body>
</html>

Prepends a jQuery object(similar to an Array of DOM Elements)to all paragraphs.

<!DOCTYPE html>
<html>
<head>
  <style>p { background:yellow; }</style>
  <script src="./static/js/jquery-3.5.0.js"></script>
</head>
<body>
  <p> is what was said.</p><b>Hello</b>
<script>$("p").prepend( $("b") );</script>
 
</body>
</html>

上篇: appendTo()

下篇: prependTo()