我有这个 HTML 列表 <ul>
其中包含具有两个不同类的列表项。
<ul id="Items">
<li class="sw">Switchable 1</li>
<li class="sw">Switchable 2</li>
<li class="notsw">This should remain 3</li>
<li class="sw">Switchable 4</li>
<li class="notsw">This should remain 5</li>
<li class="sw">Switchable 6</li>
</ul>
<input type="button" class="btn" value="Shuffle" />
我试图在触发事件时随机化或打乱列表项的顺序(假设单击了一个按钮),但仅使用 .sw
打乱列表项的顺序类(class)。到目前为止,我已经实现了使用 jQuery
对列表项(所有项)进行洗牌。自定义函数。然后,我尝试存储 .notsw
的初始索引列出项目(我想我得到了正确的值)并使用了 jQuery .before()
洗牌后将其移回原处,但我仍然无法将其移至应有的位置。
注意:具有 .notsw 类的列表项最初可以位于列表中的任何位置。
jQuery:
$('.btn').click(function(){
var notsws = document.getElementsByClassName("notsw");
var inds = new Array();
for(var i=0; i<notsws.length; i++){
inds[i] =$('.notsw').eq(i).index();
}
$('#Items').randomize();
for(var k=0; k<notsws.length; k++){
var curr = inds[k];
$('.notsw').eq(k).before($('#Items li').eq(curr));
}
});
$.fn.randomize = function(selector){
var $elems = selector ? $(this).find(selector) : $(this).children(),
$parents = $elems.parent();
$parents.each(function(){
$(this).children(selector).sort(function(){
return Math.round(Math.random()) - 0.5;
}).remove().appendTo(this);
});
return this;
};
最佳答案
我使用了另一种方法。我看到您正在随机化您的列表,然后试图记住原始元素是否存在。
取而代之的是,您为什么不直接根据元素是否可以打乱 来打乱元素。
从某种意义上说,获取由选择器 .sw
表示的 switchable elements
的索引数组,然后仅对这些索引进行混洗。
这是随机播放函数的样子。
function shuffle(nodes, switchableSelector) {
var length = nodes.length;
//Create the array for the random pick.
var switchable = nodes.filter("." + switchableSelector);
var switchIndex = [];
$.each(switchable, function(index, item) {
switchIndex[index] = $(item).index();
});
//The array should be used for picking up random elements.
var switchLength = switchIndex.length;
var randomPick, randomSwap;
for (var index = length; index > 0; index--) {
//Get a random index that contains a switchable element.
randomPick = switchIndex[Math.floor(Math.random() * switchLength)];
//Get the next element that needs to be swapped.
randomSwap = nodes[index - 1];
//If the element is 'switchable' continue, else ignore
if($(randomSwap).hasClass(switchableSelector)) {
nodes[index - 1] = nodes[randomPick];
nodes[randomPick] = randomSwap;
}
}
return nodes;
}
单击按钮时,您可以简单地打乱节点,然后将它们重新附加到容器中。
$(".btn").click(function() {
var $nodes = $("#Items").find("li");
shuffle($nodes, "sw");
$("#Items").append($nodes);
});
关于javascript - 随机化或随机化 <ul> 项目,但具有特定类别的列表项目除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23536184/