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

我试图收集一个扇区中的ID列表(数组)

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

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

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

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

I can do

我可以

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

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

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

or I can do

或者我能做到

$("#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)

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

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

9 个解决方案

#1


127

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

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

Yes, you can!

是的你可以!

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

This is the beauty of closures.

这就是封闭之美。

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:

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

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)

更多相关文章

  1. ECMAScript6(6):数组的扩展
  2. 如何使用客户端Javascript数组并通过节点发布。将js API插入Mong
  3. Javascript没有返回样式属性[重复]
  4. 在量角器中检索子元素的数组
  5. 从特定条件下存储在localStorage中的数组中删除对象?
  6. javascript小技巧&&JavaScript[对象.属性]集锦 [转载了多篇]
  7. 将子属性添加到jsdoc中的现有属性列表
  8. AngularJS:TypeError:无法读取未定义的属性'get'?
  9. Python 3.4:试图让这个模块对这个2d数组中的销售总数求和。不工作

随机推荐

  1. Android中使EditText失去焦点,edittext禁
  2. [置顶] Android按返回键退出程序但不销毁
  3. Android Unable to resolve target 'andr
  4. 关于Android(安卓)Https网络连接失败奇葩
  5. Android(安卓)计算两个地理坐标之间的距
  6. Android Q : 安卓源码、水滴屏适配状态栏
  7. Android 中文 API (21) ―― DigitalClock
  8. Android 教你如何通过 LocationManager
  9. android中实现从一个图片中截取一部分,在
  10. android layout属性 .