假设我有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体内,我怎么能这样做?
答案 0 :(得分:7)
您可以使用map()
和get()
方法获取id
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;
答案 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的方法:
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;
答案 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">