将父div添加到有span的按钮组

时间:2014-09-29 16:55:37

标签: javascript jquery html

我在div中有一组按钮和span,我正在尝试为每组按钮添加一个父div。

HTML:

<div class="btnWrapper">
<button type="button" class="fr-bttn" title="Bold">One</button>
<button type="button" class="fr-bttn" title="Italic">Two</button>
<button type="button" class="fr-bttn" title="Underline">three</button>
<button type="button" class="fr-bttn" title="Bold">Four</button>
<span class="sptr"><span>
<button type="button" class="fr-bttn" title="Strike">five</button>
<button type="button" class="fr-bttn" title="color">Six</button>
<span class="sptr"><span>
<button type="button" class="fr-bttn" title="Strike">Seven</button>
<button type="button" class="fr-bttn" title="color">Eight</button>
<button type="button" class="fr-bttn" title="color">Nine</button>
</div>

我想实现这样的目标

<div class="btnWrapper">
 <div class="parent_01">
    <button type="button" class="fr-bttn" title="Bold">One</button>
    <button type="button" class="fr-bttn" title="Italic">Two</button>
    <button type="button" class="fr-bttn" title="Underline">three</button>
    <button type="button" class="fr-bttn" title="Bold">Four</button>
  <div>   
 <span class="sptr"><span>
 <div class="parent_02">
    <button type="button" class="fr-bttn" title="Strike">five</button>
    <button type="button" class="fr-bttn" title="color">Six</button>
 </div>
<span class="sptr"><span>
<div class="parent_03">
    <button type="button" class="fr-bttn" title="Strike">Seven</button>
    <button type="button" class="fr-bttn" title="color">Eight</button>
    <button type="button" class="fr-bttn" title="color">Nine</button>
 </div>
</div>

编辑: 我试过了 的JavaScript

$(".fr-bttn").slice(0,3).wrapAll("<div class='parent1'></div>")

但面临的问题是html会动态生成,我不能通过使用slice()设置每个,我需要用<span></span>做一些事情吗?

1 个答案:

答案 0 :(得分:2)

看看这个

FIDDLE

var $span = $('.btnWrapper').find("span");
$span.each(function(i) { // what is near the spans
    var $div = $('<div class="parent_0'+i+'">Hello '+i+'</div>');
    var $content =  Array.prototype.slice.call($(this).prevUntil("div,span")).reverse();
    $div.append($content);
    $('.btnWrapper').append($div).append($(this));
});
// handle the rest
var $div = $('<div class="parent_0'+$span.length+'">Hello'+$span.length+'</div>');
$('.btnWrapper > button').appendTo($div);
$('.btnWrapper').append($div);