如何使用divs类名称使用div ID填充数组

时间:2016-08-05 14:20:23

标签: javascript jquery html css arrays

假设我有4个共享相同类别的div和唯一ID,如下所示;

<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">

我在脚本中创建了一个数组,如下所示;

var pressArray =[]

现在我想使用所有类名实例的ID名称填充此数组&#34;按&#34;在HTML体内,我怎么能这样做?

5 个答案:

答案 0 :(得分:7)

您可以使用map()get()方法获取id

的数组

&#13;
&#13;
var pressArray = $('.press').map(function() {
  return this.id;
}).get();

console.log(pressArray);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

var pressArray =[];

$(".press").each(function() {
  pressArray.push($(this).attr('id'));
});

$(".result").html(pressArray.toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">

  
<div class="result"></div>

答案 2 :(得分:1)

以下是没有jQuery的方法:

&#13;
&#13;
pressArray = [];
[].slice.call(document.querySelectorAll('.press')).forEach(function(el) {
  pressArray.push(el.id)
});
document.write(pressArray);
&#13;
<div id="Komori1" class="press"></div>
<div id="Komori2" class="press"></div>
<div id="PressD" class="press"></div>
<div id="PressE" class="press"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

轻松,抓取所有.press元素,然后将其id值映射到数组。

<强>非jQuery的:

var pressEls = document.querySelectorAll('.press');
var pressArray = [].map.call(pressEls, function(el) {
  return el.id;
});

alert(pressArray);
<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">

<强> jQuery的:

var $pressEls = $('.press');
var pressArray = $pressEls.map(function() {
  return this.id;
}).get();

alert(pressArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">

答案 4 :(得分:0)

使用press类循环遍历每个元素,并将其id推送到pressArray变量。

var pressArray = [];
$(".press").each(function(i) {
  pressArray.push(this.id);
});
alert(pressArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">

使用纯JavaScript,您可以使用for循环遍历具有类press的元素。

var pressArray = [];
for(var i=0, n=document.getElementsByClassName("press"); i<n.length; i++) {
  pressArray.push(n[i].id);
};
alert(pressArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">