.prepend()

.prepend( content ) 官网原E文:jQuery

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

  • version added: 1.0.prepend( content )

    content一个元素,HTML字符串,或者jQuery对象,将被插入到匹配元素前的内容。

  • version added: 1.4.prepend( function(index, html) )

    function(index, html)一个返回HTML字符串的函数,该字符串用来插入到匹配元素的末尾。 Receives the index position of the element in the set and the old HTML value of the element as arguments.

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

The .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>');

结果如下:

<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>

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

例子:

Example: 在所有段落前面插入一些内容。

<!DOCTYPE html>
<html>
<head>
  <style>p { background:yellow; }</style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>there friend!</p>

  <p>amigo!</p>
<script>$("p").prepend("<b>Hello </b>");</script>

</body>
</html>

Demo:

Example: 在所有段落前插入一个DOM元素。

<!DOCTYPE html>
<html>
<head>
  <style>p { background:yellow; }</style>
  <script src="http://code.jquery.com/jquery-latest.min.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>

Demo:

Example: 在所有段落前插入一个jQuery对象(类似于一个DOM元素数组)

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

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订