javascript - 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);
}
如果有人想要一些额外的乐趣,您可以尝试允许它处理可变列宽!(虽然我的项目不需要它)。
解决方案
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>
推荐阅读
- javascript - 问题在 div 元素上添加点击事件,并播放相应的音频元素
- c# - SetContentView() 的问题
- swift - 我怎样才能发现 @Published 已经用 combine 改变了?(UIKit)
- javascript - 响应中未出现标头数据 - Node JS Express JS
- python - 使用 Google Colab 进行交互式数据框排序
- sharepoint - 具有多个条件的 CAML 查询
- memory-management - processexploer PrivateBytes 可能没有显示 CMemFile 和/或 CMapViewofFile 分配,有没有办法得到这个
- go - 转到原型:找不到文件
- r - rvest follow_link 让我回到同一页面
- java - React Ntaive API(不支持)