[英]Add DOM objects to an array in a certain order, based on data-attribute
我正在构建一个自定义滑块,以便最终用户可以优先确定应该先放置哪些幻灯片,我认为最好的方法是在每个主要DOM元素上进行数据优先处理,首先设置为不透明度:0,这种情况下DOM元素的最大值为3。
但是,如您在代码中看到的那样,它将仅从上至下抓取DOM元素,而忽略数据值。
如何将它们以正确的顺序放入数组?
var hideSlide = 0;
var showSlide = 1;
var amountOfSlides = 2;
var slideArray = [];
var dataPriority = 1;
$('.hero-detail-container').each(function(e) {
if ( $(this).data('active') == '1' && $(this).data('priority') == '1' ) {
slideArray.push($(this));
}
else if ( $(this).data('active') == '1' && $(this).data('priority') == '2' ) {
slideArray.push($(this));
}
if ( $(this).data('active') == '1' && $(this).data('priority') == '3' ) {
slideArray.push($(this));
}
// THE ISSUE IS HERE
// The code will push to slideArray in the order
// it sees the DOM elements from the top, even if
// the priority says the first element is number 2 fx.
});
slideArray[0].css({
"opacity": "1"
});
setInterval(function() {
console.log(slideArray);
slideArray[hideSlide].css({
"opacity": "0"
});
slideArray[showSlide].css({
"opacity": "1"
});
if ( showSlide >= amountOfSlides ) {
hideSlide = amountOfSlides;
showSlide = 0;
}
else if ( hideSlide == 2 && showSlide == 0 ) {
hideSlide = 0;
showSlide = 1;
}
else {
hideSlide++;
showSlide++;
}
}, slideTimer());
几种方法可以做到这一点。
3:添加元素后,对数组进行排序。
slideArray.sort(function(a,b){ return a.data('priority') - b.data('priority') });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.