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"); 

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

I can do

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

然后使用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;

推荐答案

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

Yes, you can!

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

This is the beauty of closures.

请注意,当您在正确的轨道上时,sighohwellcletus都指出了实现这一点的更可靠、更简洁的方法,它们利用attribute filters(将匹配的元素限制为具有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)

Jquery相关问答推荐

在添加_renderMenu方法时,是什么原因导致jQuery UI AutoComplete抛出TypeError?

JQuery AJAX 成功事件未触发

哪个 JQuery Select 器会排除与给定 Select 器匹配的父项的项目?

jQuery Mobile:动态添加内容的标记增强

jQuery - 获取 ajax POST 的表单值

JQuery手风琴自动高度问题

jQuery获取表单字段值

如何在不导致页面滚动的情况下删除位置哈希?

如何使用 JQuery 发布 JSON 数据?

按百分比zoom div的内容?

如何使div全屏?

使用 Jquery 更改页面标题

Twitter Bootstrap css 类的 jQuery show() 隐藏

使用 AJAX 加载 Bootstrap 弹出内容.这可能吗?

使用 jQuery 的 ajax 方法将图像作为 blob 检索

将片段添加到 URL 而不导致重定向?

如何使用 jQuery 在悬停时显示工具提示消息?

javascript jquery单选按钮单击

如何在 JavaScript / jQuery 中获取对象的属性?

jQuery - 从元素内部 Select 元素