jQuery 将每 3 个 div 包装在一个 div 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3366529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wrap every 3 divs in a div
提问by csbourne
Is it possible to use nth-child
selectors to wrap 3 divs using .wrapAll
? I can't seem to work out the correct equation.
是否可以使用nth-child
选择器来包装 3 个 div .wrapAll
?我似乎无法计算出正确的方程式。
so...
所以...
<div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
becomes...
变成……
<div>
<div class="new">
<div></div>
<div></div>
<div></div>
</div>
<div class="new">
<div></div>
<div></div>
<div></div>
</div>
</div>
回答by Nick Craver
You can do it with .slice()
, like this:
你可以这样做.slice()
,像这样:
var divs = $("div > div");
for(var i = 0; i < divs.length; i+=3) {
divs.slice(i, i+3).wrapAll("<div class='new'></div>");
}
You can try out a demo here, all we're doing here is getting the elements you want to wrap and looping through them, doing a .wrapAll()
in batches of 3 then moving to the next 3, etc. It will wrap 3 at a time and however many are left at the end, e.g. 3, 3, 3, 2 if that's the case.
您可以在这里尝试一个演示,我们在这里所做的就是获取您想要包装的元素并循环遍历它们,.wrapAll()
分批执行 3 个然后移动到下一个 3 等。它将一次包装 3 个并且但是最后还剩下很多,例如 3, 3, 3, 2 如果是这样的话。
回答by Ja?ck
I've written a generic chunk function that makes this quite easy to do:
我编写了一个通用的块函数,使这很容易做到:
$.fn.chunk = function(size) {
var arr = [];
for (var i = 0; i < this.length; i += size) {
arr.push(this.slice(i, i + size));
}
return this.pushStack(arr, "chunk", size);
}
$("div > div").chunk(3).wrap('<div class="new"></div>');
$.fn.chunk = function(size) {
var arr = [];
for (var i = 0; i < this.length; i += size) {
arr.push(this.slice(i, i + size));
}
return this.pushStack(arr, "chunk", size);
}
$("div > div").chunk(3).wrap('<div class="new"></div>');
div > div {
width: 50px;
height: 50px;
background: blue;
margin: 2px;
float: left;
}
div.new {
background: red;
height: auto;
width: auto;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
回答by Alex Williams
The Plugin
插件
$(function() {
$.fn.EveryWhat = function(arg1) {
var arr = [];
if($.isNumeric(arg1)) {
$.each(this, function(idx, item) {
var newNum = idx + 1;
if(newNum%arg1 == 0)
arr.push(item);
});
}
return this.pushStack(arr, "EveryWhat", "");
}
});
How to use it.
如何使用它。
Call EveryWhat()
on the element and put in a number for every element you would like to collect.
调用EveryWhat()
元素并为您想要收集的每个元素输入一个数字。
$("div").EveryWhat(2).wrapInner('<div class="new" />');
wrapinner's quotes should have a properly formatted <div class="new" />
with a class and closing tag. Stackoverflow prevents me from showing what that looks like but here is a link of a self closing div.
wrapinner 的引号应该有一个<div class="new" />
带有类和结束标记的正确格式。Stackoverflow 阻止我展示它的样子,但这里有一个自关闭 div 的链接。
What it should look like
它应该是什么样子
That will wrap every other number that you specified. I'm using jquery 1.8.2. so remember use selector call EveryWhat(3)
and a number for every time. Of course putting it at the bottom of the page or wrapping it in a
这将包装您指定的所有其他数字。我正在使用 jquery 1.8.2。所以请记住EveryWhat(3)
每次都使用选择器调用和一个号码。当然把它放在页面的底部或将它包裹在一个
$(document).ready(function() {
//place above code here
});
You could use every nth and then .wrapInner('<div class="new" />')
for the same results.
您可以每隔 n 次使用一次,然后.wrapInner('<div class="new" />')
得到相同的结果。
回答by Pat
Here is a more usable version of Nick's above:
这是上面尼克更有用的版本:
window.WrapMatch = function(sel, count, className){
for(var i = 0; i < sel.length; i+=count) {
sel.slice(i, i+count).wrapAll('<div class="'+className+'" />');
}
}
You would use this like:
你会像这样使用它:
var ele = $('#menu > ul > li');
window.WrapMatch(ele, 5, 'new-class-name');
window should be replaced with your Handlers namespace, of course.
当然,window 应该替换为您的 Handlers 命名空间。
Updated: A slightly better version that leverages jQuery
更新:利用 jQuery 的稍微好一点的版本
(function($){
$.fn.wrapMatch = function(count, className) {
var length = this.length;
for(var i = 0; i < length ; i+=count) {
this.slice(i, i+count).wrapAll('<div '+((typeof className == 'string')?'class="'+className+'"':'')+'/>');
}
return this;
};
})(jQuery);
Use like:
像这样使用:
$('.list-parent li').wrapMatch(5,'newclass');
The second parameter for the wrapper name is optional.
包装器名称的第二个参数是可选的。
回答by PixelPrecision
$(function() {
$.fn.WrapThis = function(arg1, arg2) { /*=Takes 2 arguments, arg1 is how many elements to wrap together, arg2 is the element to wrap*/
var wrapClass = "column"; //=Set class name for wrapping element
var itemLength = $(this).find(arg2).length; //=Get the total length of elements
var remainder = itemLength%arg1; //=Calculate the remainder for the last array
var lastArray = itemLength - remainder; //=Calculate where the last array should begin
var arr = [];
if($.isNumeric(arg1))
{
$(this).find(arg2).each(function(idx, item) {
var newNum = idx + 1;
if(newNum%arg1 !== 0 && newNum <= lastArray){
arr.push(item);
}
else if(newNum%arg1 == 0 && newNum <= lastArray) {
arr.push(item);
var column = $(this).pushStack(arr);
column.wrapAll('<div class="' + wrapClass + '"/>'); //=If the array reaches arg1 setting then wrap the array in a column
arr = [];
}
else if(newNum > lastArray && newNum !== itemLength){ //=If newNum is greater than the lastArray setting then start new array of elements
arr.push(item);
}
else { //=If newNum is greater than the length of all the elements then wrap the remainder of elements in a column
arr.push(item);
var column = $(this).pushStack(arr);
column.wrapAll('<div class="' + wrapClass + '"/>');
arr = []
}
});
}
}
});
I took Kyle's plugin idea and extended it to wrap automatically and take two arguments. It didn't work for me to begin with, but I got it running with a few edits and additions to the code.
我采用了 Kyle 的插件想法并将其扩展为自动包装并采用两个参数。一开始它对我不起作用,但是我通过对代码进行了一些编辑和添加来运行它。
To invoke the function just use the parent element of what you want to wrap and then set your arguments as follows.
要调用该函数,只需使用要包装的内容的父元素,然后按如下方式设置参数。
$('#container').WrapThis(5, 'li');
The first argument is how many elements you want to wrap together and the second argument is the element type you would like to wrap.
第一个参数是您想要包装在一起的元素数量,第二个参数是您想要包装的元素类型。
You can change the class of the wrapping element in the main function under the variable wrapClass
.
您可以在 main 函数中的变量下更改包装元素的类wrapClass
。
回答by Chekit
I have prepared this answer for another question that was duplicate of this one. So maybe my variant will be usefull for some one:
我已经为另一个与此问题重复的问题准备了这个答案。所以也许我的变体对某些人有用:
I think the solution to wrap all three elements is:
我认为包装所有三个元素的解决方案是:
var $lines = $('.w-col'), // All Dom elelements with class .w-col
holder = []; //Collect DOM elelements
$lines.each(function (i, item) {
holder.push(item);
if (holder.length === 3) {
$(holder).wrapAll('<div class="w-row" />');
holder.length = 0;
}
});
$(holder).wrapAll('<div class="w-row" />'); //Wrap last elements with div(class=w-row)
I have wrote the same code at jsbin with some improvements http://jsbin.com/necozu/17/or http://jsbin.com/necozu/16/
我在 jsbin 编写了相同的代码,并进行了一些改进http://jsbin.com/necozu/17/或http://jsbin.com/necozu/16/