我有一些这样的HTML:
<span>Header Here</span>
<span>Content Here</span>
<span>Another Header</span>
<span>Some Other Content Here</span>
如您所见,HTML并不是真正以一种非常易于访问的方式进行格式化的,不幸的是,我无法更改输出,我需要做的是每2个span都用div换行,因此输出变为:
<div class="row">
<span>Header Here</span>
<span>Content Here</span>
</div>
<div class="row offsetRow">
<span>Another Header</span>
<span>Some Other Content Here</span>
</div>
offsetRow类将每隔一行重复一次。
在jQuery中甚至可能吗?
最佳答案
您可以像这样使用.wrapAll()
var $els = $('span');
for (var i = 0; i < $els.length; i += 2) {
$els.slice(i, i + 2).wrapAll('<div class="row ' + (i > 0 && i % 2 == 0 && i % 4 != 0 ? 'offsetRow' : '') + '"></div>')
}
.row {
color: grey
}
.offsetRow {
background-color: lightblue;
}
span {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span>Header Here</span>
<span>Content Here</span>
<span>Another Header</span>
<span>Another Header</span>
<span>Another Header</span>
<span>Another Header</span>
<span>Another Header</span>
<span>Another Header</span>