javascript 从数组内容设置 div id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15587457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:18:28  来源:igfitidea点击:

Set div id's from array content

javascriptjqueryarrayshtmlstyles

提问by Dave

I'm trying to figure out how to give 16 different divs the id names that are stored in a 16 elements long array.

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

This is so that I can randomize the divs "placement" for a memory game, since there will be 8 different div styles that will change along with the div id if that is possible.

这样我就可以为记忆游戏随机化 div 的“位置”,因为如果可能的话,将有 8 种不同的 div 样式随着 div id 的变化而变化。

My plan is to have the same name for the div id as for the style for that specific div.

我的计划是为 div id 使用与该特定 div 的样式相同的名称。

Is there any way to set the first div's id and style as the value in myarray[0], and the second div's id and style as myarray[1], and so on?

有什么办法可以将第一个div的id和style设为myarray[0]中的值,将第二个div的id和style设为myarray[1],依此类推?

EDIT:

编辑:

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

then later in the body I'm trying to achieve something that represents this:

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

<div id="card[0]"></div>
<div id="card[1]"></div>
<div id="card[2]"></div>

and so on...

等等...

回答by Daniel Imms

Here is a solution for randomising class names using pure JavaScript.

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

Updated answer

更新答案

I have updated my solution now that the question was clarified, here is it adapted to your colors. I have set the background-colorof the .cards to the colors set in the array. This could easily be done using the idas well, I recommend against using []characters in an idthough as I think I'm not sure if that's standards compliant.

既然问题已经澄清,我已经更新了我的解决方案,这里是否适合您的颜色。我已经设定background-color了的.cardS到阵列中设置的颜色。这也可以使用 轻松完成id,我建议不要[]在 an中使用字符,id因为我认为我不确定这是否符合标准。

jsFiddle

js小提琴

enter image description here

在此处输入图片说明

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

Original answer

原答案

Given an array of ids and a set of HTML elements, a random idwill be assigned to each element from ids.

给定一组 id 和一组 HTML 元素,id将从ids.

jsFiddle

js小提琴

enter image description here

在此处输入图片说明

JavaScript

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

HTML

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>

CSS

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; }

回答by Ben McCormick

Assign each div a randomdivclass or something like that. That will ensure you can select on the ones you want without affecting other divs.

为每个 div 分配一个randomdiv类或类似的东西。这将确保您可以在不影响其他 div 的情况下选择您想要的那些。

Then you can do this

然后你可以这样做

var idArr = [/**random ids here**/];
$( ".randomdiv" ).each(function( index ) {
  $(this).attr("id",idArr[index]);
});

That will loop over every div with the class randomdivand assign it a value from idArrwhich you can define however you want, I guess with some type of randomization function for your use case

这将循环使用该类的每个 divrandomdiv并为其分配一个值idArr,您可以根据需要定义该值,我想为您的用例使用某种类型的随机化函数

Update

更新

With your updates to the question I'm seeing an issue. You have non unique ids that you want to set. ids must be unique. If you want to assign multiple of them to be the same you want to use classes. So the code would instead look like this

随着您对问题的更新,我看到了一个问题。您有要设置的非唯一 ID。id 必须是唯一的。如果您想将它们中的多个分配为相同的,您要使用类。所以代码看起来像这样

var card = ["orange","orange","pink","pink","red","red","purple","purple",

"blue","blue","green","green","brown","brown","yellow","yellow"]; $( ".randomdiv" ).each(function( index ) { $(this).addClass(card[index]); });

"蓝色","蓝色","绿色","绿色","棕色","棕色","黄色","黄色"]; $( ".randomdiv" ).each(function( index ) { $(this).addClass(card[index]); });

And then you could define the style you want with css like this

然后你可以像这样用 css 定义你想要的样式

.randomdiv.blue{
  background-color:blue;
}

.randomdiv.green{
  background-color:green;
}
...

回答by diggersworld

Hard to know exactly what you're after but if using jQuery you could do something like this:

很难确切地知道您在追求什么,但如果使用 jQuery,您可以执行以下操作:

HTML:

HTML:

<div class="random"></div>
<div class="random"></div>
<div class="random"></div>

JavaScript:

JavaScript:

var myarray = ["one","two","three"];    

// loop through all divs
$('div.random').each(function(index) {

    // set div id to array value
    $('div').attr('id', myarray[index]);

});

Result:

结果:

<div class="random" id="one"></div>
<div class="random" id="two"></div>
<div class="random" id="three"></div>

Additional Comments:

附加评论:

Would be worth ensuring or at least checking that the array length is equal to the number of divelements, otherwise you may receive exceptions.

值得确保或至少检查数组长度是否等于div元素数,否则您可能会收到异常。

回答by Shuping

Your page could be either rendered in server side or client side

您的页面可以在服务器端或客户端呈现

1) in server side, that is much more easier with your server side language (e.g. C#) and framework (e.g. ASP.NET)

1) 在服务器端,使用服务器端语言(例如 C#)和框架(例如 ASP.NET)要容易得多

2) in client side, you could generate your DOM based on any JavaScript template (e.g. underscore template) and render it by passing the array as data model) you may refer to underscore template method: http://underscorejs.org/#template

2)在客户端,您可以基于任何JavaScript模板(例如下划线模板)生成DOM并通过将数组作为数据模型传递来呈现它)您可以参考下划线模板方法:http: //underscorejs.org/#template

EDIT

编辑

for an example on server side (I use C# and MVC razor view as example, but it could be the same idea if you use any other language and web server).

对于服务器端的示例(我使用 C# 和 MVC razor 视图作为示例,但如果您使用任何其他语言和 Web 服务器,它可能是相同的想法)。

@{ ids = ... }
@foreach (var id in ids) 
{
  <div id="@id"></div>
}

the code will help you to generate the div with ids you defined.

该代码将帮助您使用您定义的 id 生成 div。

and on client side (I use underscore template, but again same idea if you use any other engine)

和在客户端(我使用下划线模板,但如果你使用任何其他引擎,同样的想法)

var list = "_.each(ids, function(id) {<div id='<%id%>'></div>});";
_.template(list, {ids: ['id1', 'id2', 'id3']});

this will generate 3 div with the ids listed.

这将生成 3 个列有 id 的 div。

Update

更新

It's better to generate the id when generating the div rather than firstly generate the div then modify its id.

生成div的时候最好生成id,而不是先生成div再修改id。