gpt4 book ai didi

javascript - 只给 id 赋值一次

转载 作者:行者123 更新时间:2023-11-28 12:32:48 25 4
gpt4 key购买 nike

有一个问题困扰了我一段时间。

我有 14 个 div,每次加载页面时都必须为每个 div 分配一个随机 ID(1 到 14 之间)。每个 div 都有“.image-box”类,我尝试分配的 ID 格式为“box14”

我有 JS 代码来分配随机 ID,但我无法让相同的 ID 分配两次。

JavaScript

var used_id = new Array();

$( document ).ready(function() {
assign_id();

function assign_id()
{
$('.image-box').each(function (i, obj) {
random_number();
function random_number(){
number = 2 + Math.floor(Math.random() * 14);
var box_id = 'box' + number;

if((box_id.indexOf(used_id) !== -1) === -1)
{
$(this).attr('id',box_id);
used_id.push(box_id);
}


else
{
random_number();
}
}
});

}

});

感谢您的帮助,

干杯

最佳答案

嗯,random...

在分配 ID 时,不要使用随机生成的数字(根据您的经验,该数字可能会随机重复值),而是使用增量更新的计数器。

function assign_id() {
var counter = 0;
$('.image-box').each(function (i, obj) {
$(this).attr('id','image-box-' + counter++); }
});
}

关于javascript - 只给 id 赋值一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20486894/

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