javascript - Randomizing slides only works if more than two slides
问题描述
I have this randomize() function to randomize slides in Slick Slider. It works, but in Firefox it only works if there are more than two slides. Can anyone see why that is?
Js:
$.fn.randomize = function(selector) {
var $el = selector ? $(this).find(selector) : $(this).children(),
$pars = $el.parent();
$pars.each(function() {
$(this).children(selector).sort(function(chA, chB) {
if ($(chB).index() !== $(this).children(selector).length - 1) {
return Math.round(Math.random()) - 0.5;
}
}.bind(this)).detach().appendTo(this);
});
return this;
};
$('.slider').randomize().slick();
Html:
<div class="slider">
<div>
<img src="https://kenwheeler.github.io/slick/img/fonz1.png" />
</div>
<div>
<img src="https://kenwheeler.github.io/slick/img/fonz2.png" />
</div>
<! -- Uncomment to see it working in FF
<div>
<img src="https://kenwheeler.github.io/slick/img/fonz3.png" />
</div> -->
</div>
解决方案
One option is to convert the jQuery
object into an array using get()
Use the shuffle code of this SO answer. And use html
to update the parent div
$.fn.randomize = function(selector) {
var $el = selector ? $(this).find(selector) : $(this).children(),
$pars = $el.parent(),
array = $el.get();
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
$pars.html(array);
return this;
};
$('.slider').randomize();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider">
<div>
1
</div>
<div>
2
</div>
<div>
3
</div>
</div>
推荐阅读
- soap - Workday Human Resources API - 请求服务版本无效
- azure - 管理来自 Microsoft graph api 的多个发布请求以获取通知
- kubernetes - 无法通过 kubectl 代理使用服务访问 kubernetes pod
- python - 在使用记忆化和递归时,如何改进计算帕斯卡三角形第 N 行的代码?
- ios - 如何向使用路径遮罩的视图添加阴影
- javascript - 如何在for循环中的php编辑表单的隐藏字段中分配唯一值
- c# - 可以从消息中使用 BrokeredMessage
- java - 当我在列表视图中滚动时,我的应用程序崩溃了
- python - 嵌套循环向量化
- ios - 尝试在滚动视图滚动上更改 UIButton 标题颜色和框架