如何使用jQuery获取所有ID? [英] How to get all of the IDs with jQuery?

查看:123
本文介绍了如何使用jQuery获取所有ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试收集某个扇区中的ID列表(数组)

I am trying to gather a list (array) of ids in a sector

<div id="mydiv">
 <span id='span1'>
 <span id='span2'>
</div>

$("#mydiv").find("span"); 

给我一​​个jQuery对象,但不是真正的数组;

gives me a jQuery object, but not a real array;

我能做到

var array = jQuery.makeArray($("#mydiv").find("span"));

然后使用for循环将id属性放入另一个数组

and then use a for loop to put the id attributes into another array

或我能做到

$("#mydiv").find("span").each(function(){}); //but i cannot really get the id and assign it to an array that is not with in the scope?(or can I)

无论如何,我只想知道jQuery中是否有简写这样做;

Anyhow, I just wanna see if there is a shorthand in jQuery to do that;

推荐答案


//但是我不能真正获得id并将其分配给不在范围内的数组?(或者我可以)

//but i cannot really get the id and assign it to an array that is not with in the scope?(or can I)

是的,你可以!

var IDs = [];
$("#mydiv").find("span").each(function(){ IDs.push(this.id); });

这是的。

请注意,当您走在正确的轨道上时, sighohwell cletus 都指出了更可靠和简洁的方法来实现这一点,利用属性过滤器(将匹配的元素限制为具有ID的元素)和jQuery的内置 map() 功能:

Note that while you were on the right track, sighohwell and cletus both point out more reliable and concise ways of accomplishing this, taking advantage of attribute filters (to limit matched elements to those with IDs) and jQuery's built-in map() function:

var IDs = $("#mydiv span[id]")         // find spans with ID attribute
  .map(function() { return this.id; }) // convert to set of IDs
  .get(); // convert to instance of Array (optional)

这篇关于如何使用jQuery获取所有ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆