用div包裹多个节点 [英] wrap more than one nodes with div
本文介绍了用div包裹多个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何使用jquery或javascript将div的一半准确地换成另一个div
How can i wrap exactly half of the div's with another div using jquery or javascript
我有这个
<div class="post">1</div>
<div class="post">2</div>
<div class="post">3</div>
<div class="post">4</div>
<div class="post">5</div>
<div class="post">6</div>
我想要这个
<div class="wrap">
<div class="post">1</div>
<div class="post">2</div>
<div class="post">3</div>
</div>
<div class="wrap">
<div class="post">4</div>
<div class="post">5</div>
<div class="post">6</div>
</div>
推荐答案
尝试使用此功能:
var posts = $('.post'),
postCount = posts.length,
postHalf = Math.round(postCount/2),
wrapHTML = '<div class="wrap"></div>';
posts.slice(0, postHalf).wrapAll(wrapHTML); // .slice(0, 3)
posts.slice(postHalf, postCount).wrapAll(wrapHTML); // .slice(3, 6)
这将选择所有.post
,获取找到的元素数量,然后将该值减半以获取分割点.然后,它使用 .slice()
选择特定范围的元素,然后使用中.
This selects all .post
, gets the number of elements found then halves that value to get the splitting point. It then uses .slice()
to select a specific range of elements and .wrapAll()
to wrap each selection in <div class="wrap"></div>
.
它在这里工作: http://jsfiddle.net/ekzrb/
这篇关于用div包裹多个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文