【问题标题】:Add parent div to button group where there is span将父 div 添加到有跨度的按钮组
【发布时间】:2014-09-29 16:55:37
【问题描述】:

我在一个 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是动态生成的,我不能使用slice()来设置每个,我需要用&lt;span&gt;&lt;/span&gt;做点什么?

【问题讨论】:

  • 什么阻止了你?抱歉,我确定您的问题中一定还有其他问题,但我错过了
  • 你尝试过 jquery next() 吗? api.jquery.com/next
  • nextUntil 可能更合适
  • @Fabio:更新了我的问题,请检查
  • 我对 nextUntil 的投票。 @mplungjan,您会将其添加为答案

标签: javascript jquery html


【解决方案1】:

看看这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    相关资源
    最近更新 更多