从数组内容中设置div id

Dav*_*ave 3 html javascript arrays jquery styles

我试图弄清楚如何给16个不同的div提供存储在16个元素长数组中的id名称.

这样我就可以将div的"位置"随机化为记忆游戏,因为如果可能的话,将会有8种不同的div样式与div id一起变化.

我的计划是为div id设置与该特定div的样式相同的名称.

有没有办法将第一个div的id和样式设置为myarray [0]中的值,将第二个div的id和样式设置为myarray [1],依此类推?

编辑:

var card = ["orange","orange","pink","pink","red","red","purple","purple",
"blue","blue","green","green","brown","brown","yellow","yellow"];

for(var j, x, i = card.length; i; j = parseInt(Math.random() * i),
x = card[--i], card[i] = card[j], card[j] = x);
Run Code Online (Sandbox Code Playgroud)

然后在身体我试图实现代表这一点的东西:

<div id="card[0]"></div>
<div id="card[1]"></div>
<div id="card[2]"></div>
Run Code Online (Sandbox Code Playgroud)

等等...

Dan*_*mms 7

这是一个使用纯JavaScript随机化类名的解决方案.

更新的答案

我已经更新了我的解决方案,现在澄清了问题,这里它适应了你的颜色.我已经设定background-color了的.cardS到阵列中设置的颜色.这也可以很容易地使用id,我推荐不要使用[]字符,id因为我认为我不确定这是否符合标准.

的jsfiddle

在此输入图像描述

var colors = [
    "orange","orange","pink","pink","red","red","purple","purple",
    "blue","blue","green","green","brown","brown","yellow","yellow"
];

var divs = document.getElementsByClassName("card");

while (divs.length > 0) {
    var i = Math.floor(Math.random() * colors.length);
    divs[0].style.backgroundColor = colors[i];
    colors.splice(i, 1);
    divs = [].slice.call(divs, 1);
}
Run Code Online (Sandbox Code Playgroud)

原始答案

给定一组id和一组HTML元素,id将为每个元素分配一个随机数ids.

的jsfiddle

在此输入图像描述

JavaScript的

var ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var divs = document.getElementsByClassName("game-element");

while (divs.length > 0) {
    var i = Math.floor(Math.random() * ids.length);
    divs[0].id = 'item-' + ids[i];
    ids.splice(i, 1);
    divs = [].slice.call(divs, 1);
}
Run Code Online (Sandbox Code Playgroud)

HTML

<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
<div class="game-element"></div>
Run Code Online (Sandbox Code Playgroud)

CSS

.game-element {
    width:10px;
    height:10px;
    float:left;
}

#item-1  { background-color:#F00; }
#item-2  { background-color:#0F0; }
#item-3  { background-color:#00F; }
#item-4  { background-color:#FF0; }
#item-5  { background-color:#F0F; }
#item-6  { background-color:#0FF; }
#item-7  { background-color:#A0A; }
#item-8  { background-color:#0AA; }
#item-9  { background-color:#AA0; }
#item-10 { background-color:#000; }
Run Code Online (Sandbox Code Playgroud)