我想从一组项目中获取所有ID,如何使这一行简短:
var ids = [];
$(".post").each(function(index, element) {
ids.push($(element).attr("id"));
});
就像是:
var ids = $(".post").map("id");
最佳答案
对! .map()
对于jQuery对象,或者$.map
对于数组和对象。 jQuery版本将返回一个应用了map函数的jQuery对象,因此您必须调用.get()
才能获得实际的数组。
var ids = $(".post").map(function(index, element) { return element.id }).get();
关于jquery - 是否有像Ruby中的jQuery(&:map)函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3316487/