我有一堆<ul>
具有属性 data-year 的 s。我想将具有相同值的数据年属性包装在 div 中,如下所示:<div class="year"><div>
前:
<div class="projectLists">
<ul data-year="2013">
<li>items ...
</ul>
<ul data-year="2013">
<li>items...
</ul>
<ul data-year="2012">
<li>items ...
</ul>
<ul data-year="2012">
<li>items ...
</ul>
<ul data-year="2011">
<li>items...
</ul>
<ul data-year="2011">
<li>items...
</ul>
</div>
之后应该是这样的:
<div class="projectLists">
<div class="year">
<ul data-year="2013">
<li>items ...
</ul>
<ul data-year="2013">
<li>items...
</ul>
</div>
<div class="year">
<ul data-year="2012">
<li>items ...
</ul>
<ul data-year="2012">
<li>items...
</ul>
</div>
<div class="year">
<ul data-year="2011">
<li>items ...
</ul>
<ul data-year="2011">
<li>items...
</ul>
</div>
</div>
我已经尝试过多次包装每个 ul 并且没有预期的结果:
$('.projectList ul').each(function(){
var year = $(this).attr('data-year');
//alert(year)
console.log(year);
$('.projectList ul[data-year=' + year + ']').wrapAll('<div class="year">');
$('.projectList ul[data-year=' + year + ']').eq(0).before('<h2>'+ year +'</h2>');
});
任何帮助都会很棒,谢谢。