jQuery - 使用相同的类对多个元素进行分组 [英] jQuery - Grouping multiple elements with the same class
问题描述
我有一堆元素都属于某个数字的一部分。
I have a bunch of elements that all belong to a section of a certain number.
<div class="section-1"></div>
<div class="section-1"></div>
<div class="section-2"></div>
<div class="section-2"></div>
<div class="section-2"></div>
<div class="section-3"></div>
<div class="section-4"></div>
<div class="section-4"></div>
...
我想包装同一部分的每一组具有父元素的元素,甚至只出现一次的部分。
I want to wrap each group of the same section elements with a parent element, even sections that occur only once.
这是一个快速且有效但非常脏的解决方案,我想出了:
This is a quick and working, but very dirty solution that I came up with:
$('.section-1').wrapAll('<div class="parent-section">');
$('.section-2').wrapAll('<div class="parent-section">');
$('.section-3').wrapAll('<div class="parent-section">');
$('.section-4').wrapAll('<div class="parent-section">');
$('.section-5').wrapAll('<div class="parent-section">');
$('.section-6').wrapAll('<div class="parent-section">');
我试图通过使用每个()
I tried to come up with a slightly more elegant solution by using each()
$('.section-1,' +
'.section-2,' +
'.section-3,' +
'.section-4,' +
'.section-5,' +
'.section-6').each(function () {
$(this).wrapAll('<div class="parent-section">');
});
然后我意识到这将包装每个类名的每个单独出现而不是将它们包装为分组。
But then I realised that this will wrap each individual occurrence of every class name and not wrap them as a group.
除此之外,目前只有6个部分,未来可能会有更多部分(7,8,9,10,11等) ,所以如果函数可以使用任意数量的部分会很棒。
On top of that, while currently there are only 6 sections, there might be more in the future (7, 8, 9, 10, 11 etc.), so it would be great if the function could work with any number of sections.
非常感谢任何帮助。
推荐答案
// Get all the classes
var classes = $('[class^=section]').map(function() {
return $(this).attr('class');
});
// Filter only unique ones
var uniqueClasses = $.unique(classes);
// Now group them
$(uniqueClasses).each(function(i, v)
{
$('.'+v).wrapAll('<div class ="parent-'+v+'"></div>');
});
在此示例中,每个组都位于父类div中,类名为 parent-section-1
, parent-section-2
等等。
In this example, each group will be inside a parent div with class name parent-section-1
, parent-section-2
and so.
这篇关于jQuery - 使用相同的类对多个元素进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!