我正在寻找一个以数组或JSON文件存储的22个值的列表,并从共享相同类的div列表中填充一个随机div。该值只能使用一次,并且每个div只能包含1个值,不能再包含其他值。
例如,如果我有22个div,则希望脚本将值中的1个随机放入该div的rel属性中。
脚本运行之前的示例:
$values = 1,2,3,4,5
<div class="box" rel=""></div>
<div class="box" rel=""></div>
<div class="box" rel=""></div>
<div class="box" rel=""></div>
<div class="box" rel=""></div>
示例后脚本已运行:
<div class="box" rel="4"></div>
<div class="box" rel="1"></div>
<div class="box" rel="2"></div>
<div class="box" rel="5"></div>
<div class="box" rel="3"></div>
已编辑:我尝试过的内容
因此,我尝试自己执行此操作,但是,我只能使用rel属性值的设置,因此它不起作用。可能是因为它不喜欢使用“ box”格式。有什么想法吗?
function setupBoxes(){
var values = ["0.01","0.50","1.00","2.50","5.00","7.50","10.00","15.00","20.00","25.00","30.00","50.00","75.00","100.00","125.00","150.00","175.00","200.00","225.00","250.00","275.00","300.00"];
function shuffleArray(array) {
for (let i = values.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[values[i], values[j]] = [values[j], values[i]];
}
} shuffleArray();
console.log(values);
var boxs = document.getElementsByClassName("box");
var arrayCount = 0;
Array.prototype.forEach.call(boxs, function(box) {
$boxValueSet = values[arrayCount];
box.attr('rel', $boxValueSet);
arrayCount++;
});
} setupBoxes();
答案 0 :(得分:0)
在IceMetalPunks建议的帮助下,我最终使数组随机化,遍历类列表并从数组中设置一个值,然后通过一个类的每个循环递增每个数组的值。
function setupBoxes(){
var values = ["0.01","0.50","1.00","2.50","5.00","7.50","10.00","15.00","20.00","25.00","30.00","50.00","75.00","100.00","125.00","150.00","175.00","200.00","225.00","250.00","275.00","300.00"];
function shuffleArray(array) {
for (let i = values.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[values[i], values[j]] = [values[j], values[i]];
}
} shuffleArray();
console.log(values);
var boxs = document.getElementsByClassName("box");
var arrayCount = 0;
Array.prototype.forEach.call(boxs, function(box) {
$boxValueSet = values[arrayCount];
console.log(box);
box.setAttribute("rel", $boxValueSet);
arrayCount++;
});
} setupBoxes();
答案 1 :(得分:0)
尝试一下:
var values = [1, 2, 3, 4, 5];
var shuffledValues = randoSequence(values);
var boxes = document.getElementsByClassName("box")
for(var i = 0; i < boxes.length; i++){
if(i < values.length){
boxes[i].rel = shuffledValues[i].value;
}
}
randoSequence只是randojs.com提供的对数组进行混洗的功能。欢迎您自己改组数组,如果想了解更多,请查看randojs。如果您选择使用randoSequence函数,只需在html文档的head标签中扔掉它即可。
<script src="https://randojs.com/1.0.0.js"></script>
除此之外,我认为代码很不言自明。如果您有任何疑问,请告诉我!