我读了this question ,并提供了接受的答案:
var ids = $('.cookie').map(function(index) {
// this callback function will be called once for each matching element
return this.id;
});
如何在纯 javascript 中完成上述操作?
最佳答案
我建议如下:
// using Function.prototype.call() to apply
// Array.prototype.map() to the array-like NodeList returned
// by document.querySelectorAll():
var elementIDs = Array.prototype.map.call(document.querySelectorAll('.cookie'), function (cookie) {
// the first argument to the anonymous function ('cookie') is
// the array element of the array over which we're iterating,
// and is here a DOM node.
// here, we return the id property of the current node:
return cookie.id;
});
引用资料:
关于javascript - 将某个类的所有元素的ID获取到javascript中的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30548942/