返回值:jQueryprepend(content, [content])

在每个匹配元素内的开头插入指定的内容。

.prepend() 方法插入的指定内容会作为 jQuery 集合中匹配元素的第一个子节点 (若将插入的内容作为 最后一个 子节点, 请使用 .append() )。

.prepend() .prependTo() 方法的功能是一样的。主要的区别在于语法指定(syntax-specifically)上,也就是说在调用方法时,选择的元素及指定的内容这两个参数的位置是不同的。对于 .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>');

其结果是,每个含有 inner 样式的 <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>

特别注意: 如果目标元素(即被当成容器的元素)不只一个,那么会将克隆后的插入元素,插入到每个目标元素中。

额外的参数

和其它可添加内容的方法类似,例如 .append() .before() , .prepend() 同样可以将多个内容作为参数。支持的内容包括 DOM 元素, jQuery 对象, HTML 字符串, 和 DOM 元素数组。

例如,如下的代码会在 body 的开头,插入两个新的 <div> 和一个已经存在的 <div>

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)。参数的类型和数量,将在很大程度上取决于你是如何选择元素的。

示例:

在所有的段落内的开头,追加一些 HTML。

<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; }</style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>there, friend!</p>

<p>amigo!</p>

<script>

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

</script>
</body>
</html>

演示:

示例:

在所有的段落内的开头,追加一个元素。

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

演示:

示例:

在所有的段落内的开头,追加一个 jQuery 对象(类似于一个 DOM 元素数组)。

<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; }</style>
<script src="jquery.min.js"></script>
</head>
<body>

<p> is what was said.</p><b>Hello</b>

<script>

$("p").prepend( $("b") );

</script>
</body>
</html>

演示: