我收到了以下代码:
<div class="timeline">
<div class="timeslice" data-tid="360"></div>
<div class="timeslice" data-tid="360"></div>
<div class="timeslice" data-tid="360"></div>
<div class="empty-timeslice"></div>
<div class="timeslice" data-tid="360"></div>
<div class="timeslice" data-tid="360"></div>
<div class="empty-timeslice"></div>
<div class="empty-timeslice"></div>
<div class="timeslice" data-tid="360"></div>
<div class="timeslice" data-tid="360"></div>
<div class="timeslice" data-tid="361"></div>
<div class="timeslice" data-tid="361"></div>
</div>
我想用相同属性的组和相同的“组”来扭曲div,如下所示:
<div class="timeline">
<div class="warp">
<div class="timeslice" data-tid="360"></div>
<div class="timeslice" data-tid="360"></div>
<div class="timeslice" data-tid="360"></div>
</div>
<div class="empty-timeslice"></div>
</div>
<div class="warp">
<div class="timeslice" data-tid="360"></div>
<div class="timeslice" data-tid="360"></div>
</div>
<div class="empty-timeslice"></div>
<div class="empty-timeslice"></div>
<div class="warp">
<div class="timeslice" data-tid="360"></div>
<div class="timeslice" data-tid="360"></div>
</div>
<div class="warp">
<div class="timeslice" data-tid="361"></div>
<div class="timeslice" data-tid="361"></div>
</div>
</div>
在我的代码中,我能够得到data-tid的每个值,如下所示:
function warpAroundTimeslice(arrayOfTid){
...
}
有什么想法吗?
如果我采用另一种方式,我试图选择具有相同类别/属性且彼此相邻的元素以便扭曲它们
我希望我的问题有道理,如果不是,请告诉我! 非常感谢!
感谢Leonardo Delfino,这是最终的代码,对我有用:
var group = [];
var groupCount = 0;
var group_attr_value = '360';
$(".timeline > div").each(function(i, item) {
var $item = $(item);
if($item.attr('data-tid') == group_attr_value) {
group.push(item);
};
if($item.next().attr('data-tid') != group_attr_value) {
$(group).wrapAll("<div class='wrapper'> Comment: " + groupCount + "</div>");
group = [];
groupCount++;
}
});
答案 0 :(得分:1)
你可以这样做:
var group = [];
var groupCount = 0;
var group_class = "timeslice";
$(".timeline > div").each(function(i, item) {
var $item = $(item);
if($item.hasClass(group_class)) {
group.push(item);
};
if(group.length > 0 && !$item.next().hasClass(group_class)) {
$(group).wrapAll("<div class='wrap'> Group: " + groupCount + "</div>");
group = [];
groupCount++;
}
});
检查这个小提琴:http://jsfiddle.net/wv9W7/3/
答案 1 :(得分:0)
你可以采取以下几种方式。如果你不介意单独包装元素(而不是像你的例子中那样分组),那么一个简单的解决方案就是:
<强> Demo Fiddle 强>
JS:
$('.timeslice').wrap('<div class="wrap">');