开发者

Wrap groups of links with a div? (PHP is an option)

I have a dynamically generated number of links that I would like to put automatically into divs in groups of three. Is there any way to easily do this with jQuery?

The purpose is so that jQuery cycle could be used to cycle through these divs.

I was thinking of how it could also be done with PHP with a counter which would output an opening div and a closing div 开发者_如何学Pythonafter three links, but it would never meet the condition to close the div if there were, for example, 5 links: a group of 3 and 2.

Example: http://jsfiddle.net/waffl/RkzVy/

$("a+a+a").wrapAll('<div class="testDiv"></div>');
.testDiv {
  border: 1px solid red;
  margin: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="http://www.google.com">Google Link</a>
<a href="http://www.google.com">Google Link</a>
<a href="http://www.google.com">Google Link</a>
<a href="http://www.google.com">Google Link</a>
<a href="http://www.google.com">Google Link</a>
<a href="http://www.google.com">Google Link</a>
<a href="http://www.google.com">Google Link</a>
<a href="http://www.google.com">Google Link</a>


How about this?

http://jsfiddle.net/RkzVy/1/

var holder;

$("a").each(function(index, elem){
    if(index%3==0){
        holder=$("<div class='testDiv'></div>").appendTo("body");
    }

    holder.append(this);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜