简体   繁体   English

将所有元素放入数组

[英]Put all elements into an array

I've looked around, but nothing seems to answer my question. 我环顾四周,但似乎没有任何答案。 I have a simple map, 5x5. 我有一张5x5的简单地图。 It has 25 divs, labeled a1-e5, as shown here: 它具有25个div,标记为a1-e5,如下所示:

<div id='a1'></div>
<div id='a2'></div>
<div id='a3'></div>
<div id='a4'></div>
<div id='a5'></div>

and so on. 等等。 I'm trying to run a function to assign each div a class. 我正在尝试运行一个函数来为每个div分配一个类。 To do this, I'm trying to put all the divs into an array, but the array always turns up empty. 为此,我试图将所有div放入一个数组中,但是该数组总是变成空的。 This is what I'm trying: 这是我正在尝试的:

var divs = [];
$('div').each(function() {
    divs.push($(this));
});

It's just not adding anything to the array. 它只是不向数组添加任何内容。 At all. 完全没有 Any ideas? 有任何想法吗? Thanks in advance for any help! 在此先感谢您的帮助!

Edit: The code is inside of a function, I just gave you a snippet of the function. 编辑:代码位于函数内部,我只给了您函数的摘要。 Sorry for any confusion on that! 对不起,对此有任何混淆!

Edit 2: I want to assign each div a random class, which is why I wanted to use an array. 编辑2:我想为每个div分配一个随机类,这就是为什么我想使用数组的原因。

$('div').each(function(idx,div){
    $(div).addClass('div'+idx)
})

This will result in 这将导致

<div id="a1" class="div0"></div>
<div id="a2" class="div1"></div>
<div id="a3" class="div2"></div>
<div id="a4" class="div3"></div>
<div id="a5" class="div4"></div>

Why don't you simply do addClass ? 为什么不简单地执行addClass

JS JS

$('div').each(function(key) {       

    $(this).addClass("divCss"+$(this).prop("id").substr(1,1)[0]);
});

CSS 的CSS

.divCss1
{
    background-color:red;
}
.divCss2
{
    background-color:green;
}
.divCss3
{
    background-color:yellow;
}
.divCss4
{
    background-color:blue;
}
.divCss5
{
    background-color:teal;
}

fiddle 小提琴

the jquery selector will return an array of items, so jQuery选择器将返回一个项目数组,因此

$('div') returns an array $('div')返回一个数组

var myDivs = $('div'); // gives you an array

Make sure you run your code after the div's have been rendered in the dom 确保在dom中渲染了div之后运行代码

ie inside a $(function () {}); 即在$(function () {});

Simply doing 简单地做

$('div').addClass("className");

will add the class to all 25 divs. 会将类别添加到所有25个div中。

EDIT : 编辑

As per your comment, you can do something like this : 根据您的评论,您可以执行以下操作:

$('div').each(function() {    
    /*Other code here to determine which class will be added to which div*/
    $(this).addClass("className");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM