2014-09-29 38 views
1

我有一组按钮和跨度在一个div内,我试图给每组按钮添加一个父div。添加父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将g动态挖掘,我不能通过使用切片()设置每个,我需要做的事情<span></span>

+0

,什么是阻止你?对不起,我确定你的问题一定还有其他问题,但我错过了它 – Devin 2014-09-29 16:58:25

+0

你试过jquery next()吗? http://api.jquery.com/next/ – 2014-09-29 16:58:39

+1

[nextUntil](http://api.jquery.com/nextuntil/)可能更适合 – mplungjan 2014-09-29 17:03:36

回答

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); 
+1

感谢你这个工作就像一个魅力。 – 2014-09-30 06:01:43