[英]Wrap function Jquery for multiple elements
I've this function in Jquery 我在jQuery中有此功能
function row_content(col1, col2) { var divs = col1 + col2; for(var n = 0; n < divs.length; n+=2){ divs.slice(n, n+2).wrapAll('<div class="row-content"></div>'); } } var col_2_3 = $('.col_2_3'); var col_1_3 = $('.col_1_3'); row_content(col_2_3, col_1_3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class='col_2_3'>Test</div> <div class='col_1_3'>Test</div> <div class='col_2_3'>Test</div> <div class='col_1_3'>Test</div>
I want, with this function to wrap two divs in .row-content
but it does not work. 我想要使用此功能将两个div包装在
.row-content
但它不起作用。
Thanks for the help ! 谢谢您的帮助 !
The problem is 问题是
var divs = col1 + col2;
Where col1,col2
are jQuery objects. 其中
col1,col2
是jQuery对象。 The above line concatenates the inputs and Does not combine the selectors. 上一行将输入连接起来,并且不合并选择器。 So
length
wont work as you wish to. 所以
length
不会如您所愿。
Use jQuery .add()
使用jQuery
.add()
var divs = col1.add(col2);
$('.col_2_3, .col_1_3').wrapAll("<div class='row-content' />");
Demo http://jsfiddle.net/5kcr44pv/ 演示http://jsfiddle.net/5kcr44pv/
UPDATE: OP forgot to mention there were multiple cols
UPDATE:OP忘了,更不用说有多重
cols
Below works as long as there are equal number of both classes and they alternate. 只要两个类的数目相等且交替出现,下面的作品即可。
var cols_2_3 = $('.col_2_3');
var cols_1_3 = $('.col_1_3');
cols_2_3.each(function (index, el) {
$($(cols_2_3[index]).add(cols_1_3[index])).wrapAll("<div class='row-content' />");
});
DEMO: http://jsfiddle.net/5kcr44pv/1/ 演示: http : //jsfiddle.net/5kcr44pv/1/
var wrapper = $('<div class="row-content"></div>');
$('.col_2_3, .col_1_3').wrapAll(wrapper);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.