我有一些像这样的HTML:
<span>Header Here</span>
<span>Content Here</span>
<span>Another Header</span>
<span>Some Other Content Here</span>
正如你所看到的那样,HTML并没有真正以一种非常易于访问的方式格式化,不幸的是我无法改变输出,我需要做的是用div包装每2个跨度,所以输出变为:< / p>
<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中甚至可能吗?
答案 0 :(得分:4)
您可以使用.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>')
}
&#13;
.row {
color: grey
}
.offsetRow {
background-color: lightblue;
}
span {
border: 1px solid red;
}
&#13;
<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>
&#13;