jQuery - 将div包装到多个元素

时间:2010-12-17 04:24:18

标签: jquery

您好
假设我有以下代码:

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

如何将div包装到这3个div中? 结果应该是:

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

更新(不工作)

<script src="http://code.jquery.com/jquery-1.4.4.js"></script>

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

<script>
$("<div>").insertBefore(".Hello").append(".Hello, .Goodbye, .Goodnight");   
</script>

更新2(工作)

<script src="http://code.jquery.com/jquery-1.4.4.js"></script>

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

<script>
$("<div>").insertBefore(".Hello").append($('.Hello'), $('.Goodbye'), $('.Goodnight'));  
</script>

更新3(不工作)

<script src="http://code.jquery.com/jquery-1.4.4.js"></script>

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

<script>
//$("<div>").insertBefore(".Hello").append($('.Hello'), $('.Goodbye'), $('.Goodnight'));    
$(".Hello, .Goodbye, .Goodnight").wrap('div');
</script>

结果:

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

谢谢

1 个答案:

答案 0 :(得分:3)

请勿使用.wrap()方法。只需创建一个新div和.append()每个元素。 E.g:

$("<div>")
    .insertBefore(".Hello")
    .append($(".Hello, .Goodbye, .Goodnight"));

div将被移入内部,而不是克隆。