首页 > 解决方案 > Jquery 在行中动态包装引导列

问题描述

我有一些格式如下的代码:

<div id="section">
    <div class="col-xs-6"></div>
    <div class="col-xs-6"></div>
    <div class="col-xs-6"></div>
    <div class="col-xs-6"></div>
    <div class="col-xs-6"></div>
    <div class="col-xs-6"></div>
    <div class="col-xs-6"></div>
</div>

此部分中可以有任意数量(偶数或奇数)列。

我想要的是像这样重新格式化它:

<div id="section">
    <div class="row">
        <div class="col-xs-6"></div>
        <div class="col-xs-6"></div>
    </div>
    <div class="row">
        <div class="col-xs-6"></div>
        <div class="col-xs-6"></div>
    </div>
    <div class="row">
        <div class="col-xs-6"></div>
        <div class="col-xs-6"></div>
    </div>
    <div class="row">
        <div class="col-xs-6"></div>
    </div>
</div>

这是我的尝试:

for (var x = 0; x < $('#section').children().length; x+=2) {
    var firstSection = $('#section').children().eq(x);
    if ($('#section').children().length >= x + 1) {
        var secondSection = $('#section').children().eq(x + 1);
        var finalSection = '<div class="row">' + firstSection.parent().html() + secondSection.parent().html() + '</div>';
        secondSection.remove();
    }
    else {
        var finalSection = '<div class="row">' + firstSection.html() + '</div>';
    }

    firstSection.remove();
    $('#section').append(finalSection);
}

如果有人想要一些额外的乐趣,您可以尝试允许它处理可变列宽!(虽然我的项目不需要它)。

标签: javascriptjquerytwitter-bootstrap-3

解决方案


Hers 是一个遍历列的示例,与您现在尝试的类似。

它使用find(),append()clone()来完成这个任务。作为一个附加功能,我将它包装到一个接受行大小作为参数的函数中。

//breaks up the section into rows of size 'rowSize', 2 by default.
function breakitup(rowSize = 2) {
  var $section = $("#section"); //get the section
  var $row = $("<div class='row'>"); //make a template for a row
  var cols = $section.find("div"); //get the columns
  var working; //tmp variable for the current row
  
  for (var i = 0; i < cols.length; i++) {
    if (i % rowSize == 0) working = $row.clone(); //clone the template when appropriate
    $(working).append(cols[i]); //add the column to the row
    if ($(working).children().length == rowSize) 
      $section.append(working); //add the row to the section as appropriate
  }
  $section.append(working); //add the last row
}
//call our fancy function
breakitup();
.row {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section">
  <div class="col-xs-6">test</div>
  <div class="col-xs-6">test2</div>
  <div class="col-xs-6">test3</div>
  <div class="col-xs-6">test4</div>
  <div class="col-xs-6">test5</div>
  <div class="col-xs-6">test6</div>
  <div class="col-xs-6">test7</div>
</div>


推荐阅读