gpt4 book ai didi

javascript - 将数组中的所有数字填充到随机 div 中

转载 作者:行者123 更新时间:2023-12-02 22:15:05 24 4
gpt4 key购买 nike

我希望获取 22 个值的列表,将其存储为数组或 JSON 文件,并从共享相同类的 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 属性值的设置,但它不起作用。可能是因为它不喜欢“盒子”的格式。有什么想法吗?

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();

最佳答案

在 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();

关于javascript - 将数组中的所有数字填充到随机 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59417078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com