在我的页面上,我有很多具有相同类别的div元素:
<div class="item" id="lorem">Asdf</div>
<div class="item" id="ipsum">Asdf</div>
<div class="item" id="dolor">Asdf</div>
现在我想将每个div的id保存到数组中。它应该是这样的:
$array = ["lorem", "ipsum", "dolor"];
我该如何正确地做到这一点?
答案 0 :(得分:2)
你可以使用jQuery的each()函数并迭代每个div来获取id并将其推送到数组中。
var $array = [];
$('div').each(function(){
var id = $(this).attr('id');
$array.push(id);
});
这是一个jsFiddle:http://jsfiddle.net/3mokjL6b/2/
答案 1 :(得分:0)
此处的项目是您的班级名称
var x = $('.item').map(function () {
return this.id;
}).get();
console.log(x);
jQuery.map()函数
答案 2 :(得分:0)
您可以通过多种方式获取div的id
var IDs = [];
$(".item").each(function(){ IDs.push(this.id); });
console.log(IDs);
或
var ids = $('.item').map(function(index) {
return this.id;
});
console.log(ids);
答案 3 :(得分:0)
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/jquery/jquery-2.1.3.min.js"></script>
</head>
<body>
<div class="item" id="lorem">Asdf</div>
<div class="item" id="ipsum">Asdf</div>
<div class="item" id="dolor">Asdf</div>
<script>
$(document).ready(function(){
var res = Array();
$('.item').each(function(index,`obj`){
res.push(obj.id);
});
console.log(res);
});
</script>
</body>
</html>