.wrapInner()

.wrapInner( wrappingElement ) 返回jQuery

描述:在匹配元素里的内容外包一层结构。

  • version added: 1.2.wrapInner( wrappingElement )

    wrappingElement用来包在匹配元素的内容外面的HTML片段,选择表达式,jQuery对象或者DOM元素。

  • version added: 1.4.wrapInner( wrappingFunction )

    wrappingFunction一个返回HTML结构的函数,用来包在匹配元素内容的外面。

参数可以是string或者对象,只要能形成DOM结构,可以是嵌套的,但是结构只包含一个最里层元素。这个结构会包住所有匹配元素的内容。

例子:

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

.wrapInner(), 我们可以再inner元素的内容外加一个新的div:

$('.inner').wrapInner('<div class="new" />');

结果:

<div class="container">
  <div class="inner">
    <div class="new">Hello</div>
  </div>
  <div class="inner">
    <div class="new">Goodbye</div>
  </div>
</div>

该方法的第二种用法允许我们用一个callback函数做参数,每次遇到匹配元素时,该函数被执行,返回一个DOM元素,jQuery对象,或者HTML片段,用来包住匹配元素的内容。

$('.inner').wrapInner(function() {
  return '<div class="' + this.nodeValue + '" />';
});

这将使得每个div有和他文本内容一样名字的class:

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

例子:

例子:选中所有段落,然后在段落内容外加粗体:

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

  <p>cruel</p>
  <p>World</p>
<script>$("p").wrapInner("<b></b>");</script>

</body>
</html>

Demo:

例子:生成一个jQuery对象树然后将它包在body里面。

<!DOCTYPE html>
<html>
<head>
  <style>

  div { border:2px green solid; margin:2px; padding:2px; }
  p { background:yellow; margin:2px; padding:2px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  Plain old text, or is it?
<script>$("body").wrapInner("<div><div><p><em><b></b></em></p></div></div>");</script>

</body>
</html>

Demo:

Example: 选中所有段落然后在段落内容外包上粗体标签。

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

  <p>cruel</p>
  <p>World</p>
<script>$("p").wrapInner(document.createElement("b"));</script>

</body>
</html>

Demo:

例子:选中所有段落然后在段落内容外包上一个jQuery对象。

<!DOCTYPE html>
<html>
<head>
  <style>

  p { background:#9f9; }
  .red { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Hello</p>
  <p>cruel</p>
  <p>World</p>
<script>$("p").wrapInner($("<span class='red'></span>"));</script>

</body>
</html>

Demo:

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